Discuss / Python / Marvin_ITer作业,map/reduce

Marvin_ITer作业,map/reduce

Topic source

一直忍着不看评论,就想憋一憋看看能写出什么样来, 先把作业交了。。。然后再吸收大家的智慧,⁄(⁄ ⁄•⁄ω⁄•⁄ ⁄)⁄

第一题

# map()实现
def normalize(name):
    return name[:1].upper()+name[1:].lower() 

M1 = ['adam', 'LISA', 'barT']
M2 = list(map(normalize, M1))
print(M2)

# 列表生成式实现
M3 = [s[:1].upper()+s[1:].lower() if isinstance(s,str) else s for s in M1]
print(M3)

第二题

# 接受一个list并利用reduce()求积
from functools import reduce

def prod(L):
    return reduce(lambda x,y:x*y,L)

print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))

第三题

# str转换为float
from functools import reduce

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

def str2float(s):
    p=s.find('.')
    end=len(s)-1
    return reduce(lambda x,y:x*10+y,map(char2num,s[:p])) \
           + reduce(lambda x,y:x*10+y,map(char2num,s[p+1:]))/10**(end-p)

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

看了大家的作业,大部分人都没有考虑,没有小数点的情况哦。 只有一位大佬后来发现补上了,我也一样漏掉了,果断补上。

from functools import reduce

def char2num(s):
    return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, \
            '7': 7, '8': 8, '9': 9}[s]
def str2float(s):
    p=s.find('.')
    end=len(s)-1
    if p==-1:
        p=end
        return reduce(lambda x,y:x*10+y,map(char2num,s))*1.0
    else:
        return reduce(lambda x,y:x*10+y,map(char2num,s[:p])) \
             + reduce(lambda x,y:x*10+y,map(char2num,s[p+1:]))/10**(end-p)

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

另外,我觉得利用split()分割,pow()算小数位的办法也很棒,顺便把没有小数点的情况也补上了。

import math
def str2float1(s):
    if s.find('.')==-1:
        return reduce(lambda x,y:x*10+y,map(char2num,s))*1.0
    else:
        s1, s2 = s.split('.', 1)
    return reduce(lambda x,y:x*10+y, map(char2num, s1+s2))/pow(10,len(s2))

  • 1

Reply