直接float()会有.0
第一种思路
# -*- coding: utf-8 -*- from functools import reduce # 原错误来自来自str2num中 def str2num(s): return int(s) if float(s)==int(float(s)) else float(s) def calc(exp): ss = exp.split('+') ns = map(str2num, ss) return reduce(lambda acc, x: acc+x, ns) def main(): r = calc('100 + 200 + 345') print('100 + 200 + 345 =', r) r = calc('99 + 88 + 7.6') print('99 + 88 + 7.6 =', r)
第二种思路:
# -*- coding: utf-8 -*- from functools import reduce # 原错误来自来自str2num中 def str2num(s): return int(s) if s.find('.')==-1 else float(s) def calc(exp): ss = exp.split('+') ns = map(str2num, ss) return reduce(lambda acc, x: acc+x, ns) def main(): r = calc('100 + 200 + 345') print('100 + 200 + 345 =', r) r = calc('99 + 88 + 7.6') print('99 + 88 + 7.6 =', r) main()
第三种思路:
# -*- coding: utf-8 -*- from functools import reduce # 原错误来自来自str2num中 def str2num(s): try: return int(s) except ValueError: return float(s) def calc(exp): ss = exp.split('+') ns = map(str2num, ss) return reduce(lambda acc, x: acc+x, ns) def main(): r = calc('100 + 200 + 345') print('100 + 200 + 345 =', r) r = calc('99 + 88 + 7.6') print('99 + 88 + 7.6 =', r) main()
可以
Sign in to make a reply
岁益寒
直接float()会有.0
第一种思路
第二种思路:
第三种思路: