Discuss / Python / 打卡,还是搞不太清楚,脑瓜子疼

打卡,还是搞不太清楚,脑瓜子疼

Topic source

zjdddlll

#1 Created at ... [Delete] [Delete and Lock User]
from functools import reduce
import logging

def str2num(s):
    try:
        return int(s)
    except Exception 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():
    L = ['100 + 200 + 345', '99 + 88 + 7s', '99 + 88 + 7.6']
    for i in L: 
        try: 
            print(i, calc(i))         
        except Exception as e:
            logging.exception(e)

main()
# 结果:
100 + 200 + 345 645
invalid literal for int() with base 10: ' 7s'
invalid literal for int() with base 10: ' 7.6'
99 + 88 + 7.6 194.6

  • 1

Reply