Discuss / Python / 交作业,顺便兼容字符串

交作业,顺便兼容字符串

Topic source
from functools import reduce

def str2num(s):
    try:
        return int(s)
    except ValueError:
        try:
            return float(s)
        except ValueError:
            print('\nThat is not a number: [%s]\n' % s)
            return None

def calc(exp):
    ss = exp.split('+')
    ns = map(str2num, ss)
    temp = list(ns)
    for s in temp:
        if s == None:
            return '[Sorry, I can\'t count it]\n'
    return reduce(lambda acc, x: acc + x, temp)

def main():
    try:
        r = calc('100 + 200 + 345')
        print('100 + 200 + 345 =', r)
        r = calc('99 + 88 + 7.6')
        print('99 + 88 + 7.6 =', r)
        r = calc('99 + 88 + a')
        print('99 + 88 + a =', r)
        1 / 0
    except BaseException:
        print('others error happen, fix it yourself')

main()
print('End')

  • 1

Reply