Marvin_ITer作业,map/reduce
Topic source看了大家的作业,大部分人都没有考虑,没有小数点的情况哦。 只有一位大佬后来发现补上了,我也一样漏掉了,果断补上。
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
用户6223899516_84125
一直忍着不看评论,就想憋一憋看看能写出什么样来, 先把作业交了。。。然后再吸收大家的智慧,⁄(⁄ ⁄•⁄ω⁄•⁄ ⁄)⁄
第一题
第二题
第三题