from functools import reduce
def str2num(s): try: return int(s) except: try: return float(s) except ValueError as e: print('ValueError!\n',e)
#raise
def calc(exp): ss = exp.split('+') ns = map(str2num, ss) return reduce(lambda acc, x: acc + x, ns)
def main(): r = calc('10A + 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
严肃的笨小孩
from functools import reduce
def str2num(s): try: return int(s) except: try: return float(s) except ValueError as e: print('ValueError!\n',e)
def calc(exp): ss = exp.split('+') ns = map(str2num, ss) return reduce(lambda acc, x: acc + x, ns)
def main(): r = calc('10A + 200 + 345') print('100 + 200 + 345 =', r) r = calc('99 + 88 + 7.6') print('99 + 88 + 7.6 =', r)
main()