高階函數練習題

map/reduce



from functools import  reduce
def fun(x,y):
    return x*10+y
L=list(range(10))
print(reduce(fun,L))




from functools import reduce
def fn(x, y):
    return x * 10 + y
def char2num(s):
    digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
    return digits[s]
print(reduce(fn, list(map(char2num, '13579'))))




def normalize(name):
    return name.capitalize()
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)


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 str2float(s):
    i = s.find('.')
    def f1(x, y):
        return x * 10 + y
    def f2(x, y):
        return x / 10 + y
    return reduce(f1, list(map(int, s[:i]))) + reduce(f2, list(map(int, s[-1:i:-1])))/10

print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
    print('測試成功!')
else:
    print('測試失敗!')



filter

def is_palindrome(n):
  s=str(n)
  return s==s[::-1]


#測試:
if list(filter(is_palindrome, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]:
    print('測試成功!')
else:
    print('測試失敗!')```

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章