CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
jackfrued

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: jackfrued/Python-100-Days
Path: blob/master/公开课/文档/年薪50W+的Python程序员如何写代码/code/Python/opencourse/part01/example06.py
Views: 729
1
# 一行代码实现求阶乘函数
2
fac = lambda x: __import__('functools').reduce(int.__mul__, range(1, x + 1), 1)
3
print(fac(5))
4
5
# 一行代码实现求最大公约数函数
6
gcd = lambda x, y: y % x and gcd(y % x, x) or x
7
print(gcd(15, 27))
8
9
# 一行代码实现判断素数的函数
10
is_prime = lambda x: x > 1 and not [f for f in range(2, int(x ** 0.5) + 1) if x % f == 0]
11
for num in range(2, 100):
12
if is_prime(num):
13
print(num, end=' ')
14
print()
15
16
# 一行代码实现快速排序
17
quick_sort = lambda items: len(items) and quick_sort([x for x in items[1:] if x < items[0]]) \
18
+ [items[0]] + quick_sort([x for x in items[1:] if x > items[0]]) \
19
or items
20
items = [57, 12, 35, 68, 99, 81, 70, 22]
21
print(quick_sort(items))
22
23
# 生成FizzBuzz列表
24
# 1 2 Fizz 4 Buzz 6 ... 14 ... FizzBuzz 16 ... 100
25
print(['Fizz'[x % 3 * 4:] + 'Buzz'[x % 5 * 4:] or x for x in range(1, 101)])
26
27