Discuss / Python / 来交作业了

来交作业了

Topic source
from functools import reduce# 第三题DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '.': -1}def str2float(s):    k = 0    n = 0    for i in range(len(s)):        if s[i] == '.':            k = len(s)-n-1            break        n = n + 1    def char2num(ch):        if DIGITS[ch] != -1:            return DIGITS[ch]        else:            return -1    def fn(x, y):        if y != -1:            return x*10 + y        else:            return x    return reduce(fn, map(char2num, s))/10**kprint('str2float(\'123.456\') =', str2float('123.456'))if abs(str2float('123.456') - 123.456) < 0.00001:    print('测试成功!')else:    print('测试失败!')
from functools import reduce

# 第二题def prod(L):    return reduce(lambda x, y: x*y, L)print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))if prod([3, 5, 7, 9]) == 945:    print('测试成功!')else:    print('测试失败!')
from functools import reduce

# 第一题,首字母大写,其它小写def normalize(name):    str1 = ''    n = 0    while n < len(name):        if (n == 0) and (name[n].islower()):            str1 = str1 + name[n].upper()        else:            str1 = str1 + name[n].lower()        n = n + 1    return str1

  • 1

Reply