python · 一行流

这篇博客介绍了如何使用Python进行一行流编程,包括筛选素数的简洁方法,计算阶乘和组合数的技巧,并强调Python的优雅与简洁原则,提倡明确、简单的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

筛素数

#一行筛素数(FP)
>>pr = list(filter(lambda x : all(map(lambda p : x % p != 0 , range(2, x))), range(2, 101)))
>>pr
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

pr 就是 100 以内素数表了~
还有一种非函数式的写法:

#一行筛素数(非FP)
>>pr = [n for n in range(2, 101) if all(n % i for i in range(2, int(n**0.5)+1))]
>>pr
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

有些数论题经常要算下前多少个素数的积,以确定数据规模。
依旧一行流(当然。。需要先筛下素数

#前n个素数之积
#python3需要先from functools import reduce

>>reduce(lambda x, y: x * y, pr[:10])
6469693230

#前n个素数和也没问题
>>reduce(lambda x, y: x + y, pr[:3])
#可以简写做sum(pr[:3])
10

阶乘

#计算30!
#python3需要先from functools import reduce
>>reduce(lambda x, y: x * y, range(1, 31))
265252859812191058636308480000000

#导入operator库的写法
>>import operator
>>reduce(operator.mul, range(1,31)) 
265252859812191058636308480000000

组合数

计算 Ckn:

>>import operator
#reduce(operator.mul, range(n - k + 1, n + 1)) / reduce(operator.mul, range(1, k +1))
#C(5,2) 
>>reduce(operator.mul, range(4, 6)) // reduce(operator.mul, range(1, 3))
10

前n项和

#计算1+2+3+...+10
>>sum(range(11))
55

sum里面装啥表都行,配合切片不要太风骚

#fibonacci前10项和:
>>fib = lambda n, x = 0, y = 1: x if not n else fib(n - 1, y, x + y)
>>sum([fib(i) for i in range(1, 10)])
88

最后念一句,python大法好!

Beautiful is better than ugly.

Explicit is better than implicit.

Simple is better than complex.

Complex is better than complicated.

Flat is better than nested.

Sparse is better than dense.

Readability counts.

Special cases aren’t special enough to break the rules.

Although practicality beats purity.

Errors should never pass silently.

Unless explicitly silenced.

In the face of ambiguity, refuse the temptation to guess.

There should be one– and preferably only one –obvious way to do it.

Although that way may not be obvious at first unless you’re Dutch.

Now is better than never.

Although never is often better than right now.

If the implementation is hard to explain, it’s a bad idea.

If the implementation is easy to explain, it may be a good idea.

Namespaces are one honking great idea – let’s do more of those!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值