题目1
利用map和reduce编写一个str2float函数,把字符串’123.456’转换成浮点数123.456:
from functools import reduce
# '123.456'
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def str2float(s):
def char2num(s):
return DIGITS[s]
n=s.index('.')
s1=s[:n]
s2=s[n+1:]
return reduce(lambda x,y: x*10+y,map(char2num,s1)) +(reduce(lambda x,y: x*10+y,map(char2num,s2)))/10**len(s2)
print('str2float(\'123.456\') =', str2float('123.456'))
题目2
用filter求素数(埃氏筛法)
def _odd_iter():
n=1
while True:
n=n+2
yield n
def primes():
yield 2
it = _odd_iter()
while True:
n=next(it)
yield n
it=filter(lambda x:x%n>0,it)
for n in primes():
if n < 1000:
print(n)
else:
break
题目3
回数是指从左向右读和从右向左读都是一样的数,例如12321,909。请利用filter()筛选出回数:
def is_palindrome(n):
strs = list(str(n))
strs.reverse()
Afterstrs = ''.join(strs)
return int(Afterstrs)==n
output = filter(is_palindrome, range(1, 1000))
print('1~1000:', list(output))