致敬廖雪峰老师!!!
题目要求:利用map
和reduce
编写一个str2float
函数,把字符串'123.456'
转换成浮点数123.456
我的思路:
(1)找出小数点位置
(2)小数点前直接int,后面int后做运算,xxx/10^n,n为后面数字个数
(3)然后前后相加
这是我最先想到的思路
代码如下
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
def Str2Float(s): #Find Positon of '.' Num = s.index('.') #取小数点前面 FrontStr = s[:Num] #取小数点后面 BehindStr = s[Num - len(s) + 1:] #做运算 FrontNum = int(FrontStr) BehindNum = int(BehindStr) / 10**len(BehindStr) Number = FrontNum + BehindNum return Number print(Str2Float('123.456'))
但是题目要求利用map和reduce吖,所以还是以上思路,改装如下:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
from functools import reduce #excise1:利用map()函数,把用户输入的不规范的英文名字,变为首字母大写, #其他小写的规范名字。输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']: def Normalize(name): return name.title() # 测试: L1 = ['adam', 'LISA', 'barT'] L2 = list(map(Normalize, L1)) print(L2) #excise2:Python提供的sum()函数可以接受一个list并求和,请编写一个prod()函数,可以接受一个list并利用reduce()求积: def prod(L): def Product(x,y):return x * y return reduce(Product,L) #测试 print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9])) if prod([3, 5, 7, 9]) == 945: print('测试成功!') else: print('测试失败!') #excise3:利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456 #我的思路: # 1.找小数点的位置,然后把前后两部分数字各截取出来 # 2.前面直接int,后面做运算:xxx/10^n,n代表后面数字个数 # 3.前后相加,打印 #思路缺点:没有使用到map和reduce函数,代码量大, # def Str2Float(s): # #Find Positon of . # Num = s.index('.') # FrontStr = s[:Num] # BehindStr = s[Num - len(s) + 1:] # FrontNum = int(FrontStr) # BehindNum = int(BehindStr) / 10**len(BehindStr) # Number = FrontNum + BehindNum # return Number # print(Str2Float('123.456')) # 使用map和reduce的思路 # 与上面思路相仿 # 找出点的位置前后截取 # str --> int # 做运算 Digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} def Str2Float(s): #找 . 的位置并前后截取 PointPosition = s.index('.') FrontStr = s[:PointPosition] BehindStr = s[PointPosition - len(s) + 1:] Front = Str2Int(FrontStr) Behind = Str2Int(BehindStr) / 10**len(BehindStr) return Front + Behind #定义转换为整数的函数 def Str2Int(s): def fn(x, y): return x * 10 + y def Char2Num(s): return Digits[s] return reduce(fn, map(Char2Num, s)) #测试 print('Str2Float(\'1433223.456\') =', Str2Float('1433223.456')) if abs(Str2Float('123.456') - 123.456) < 0.00001: print('测试成功!') else: print('测试失败!')
前面excise1和2是前面两练习的解答,我再看看别的大佬的代码理解下,再跟上