Discuss / Python / 作业

作业

Topic source

I-cpp

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

from functools import reduce

def str2num(s):

try:
    return int(s)
except ValueError as e:
    print("错误:", e)
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()

输出结果:

100 + 200 + 345 = 645 错误: invalid literal for int() with base 10: ' 7.6' 99 + 88 + 7.6 = 194.6

然后又觉得str2num还可以改一点:

def str2num(s):

try:
    return int(s)
except ValueError as e:
    print("错误:", e)
finally:
    return float(s)

但是这样会把原来的整数结果也变成了浮点型:

100 + 200 + 345 = 645.0 错误: invalid literal for int() with base 10: ' 7.6' 99 + 88 + 7.6 = 194.6


  • 1

Reply