Discuss / Python / 第一题不是让大家用title()来解的吧?谁帮我看看

第一题不是让大家用title()来解的吧?谁帮我看看

Topic source

雷蒙德张

#1 Created at ... [Delete] [Delete and Lock User]

第一题是让大家用map来实现类似于title函数的功能,如果直接调用,那还有啥意义?

我试着按照我的理解写了一段,大家帮看看,能不能再简化一点。

def normalize(name):
    lower = map(lambda x:x.lower(),name[1:])
    upper = name[0].upper()
    for i in lower:
        upper = upper + i
    return upper

erdan_erdan

#2 Created at ... [Delete] [Delete and Lock User]
    for i in lower:
        upper = upper + i
    return upper

这句怎么不直接使用?

return  upper + lower

雷蒙德张

#3 Created at ... [Delete] [Delete and Lock User]

lower是map对象,没法直接和iterable的upper直接做加法。

雷蒙德张

#4 Created at ... [Delete] [Delete and Lock User]

第三题的答案,看看能不能再简化点?

    i = s.index('.')
    def char2num(a):
         return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[a]
    return reduce(lambda x, y: x * 10 + y, map(char2num, s[:i]+s[i+1:])) / 10**(len(s)-i-1)

ferstar

#5 Created at ... [Delete] [Delete and Lock User]

代码不是越简练越好的,太简略可读性就会略差。

另外提一个bug,如果给你的字符串是整数,没有小数点,你的程序会出错

建议用find()替换index()

贴上我的代码:

#!/usr/bin/env python
# encoding: utf-8

from functools import reduce


def str2float(s):
    def del_dot(s):
        return s.replace('.', '')

    def str2num(s):
        return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]

    _result = reduce(lambda x, y: x * 10 + y, map(str2num, del_dot(s)))

    if s.find('.') == -1:
        return _result
    else:
        return _result / (10 ** (len(s) - s.find('.') - 1))


print('str2float(\'123.456\') =', str2float('123.456'))

  • 1

Reply