Python刷题汇总3

题目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))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值