筛素数
#一行筛素数(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!