艾斯压阵
一盏灯, 一片昏黄; 一简书, 一杯淡茶。 守着那一份淡定, 品读属于自己的寂寞。 保持淡定, 才能欣赏到最美丽的风景! 保持淡定, 人生从此不再寂寞。
最近在学习Python,回顾了一些最初的经典函数和算法
杨辉三角定义如下:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
方法一
使用zip函数
如图:
def triangles():
n = [1]
while True:
yield n
n = [x+y for x,y in zip([0] + n,n+[0])]
n = 0
for t in triangles():
print(t)
n = n + 1
if n == 10:
break
输出结果:
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
解析
n = [x+y for x,y in zip([0] + n,n+[0])]
当n=[1]时:
zip([0,1],[1,0])
通过
算出 n = [1,1]
以此类推
ps:zip()
1.定义:
zip([iterable, ...])
zip()是Python的一个内建函数,它接受一系列可迭代的对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表)。若传入参数的长度不等,则返回list的长度和参数中长度最短的对象相同。利用*号操作符,可以将list unzip(解压)。
2.示例:
x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
xyz = zip(x, y, z)
print xyz
输出结果:
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
二维矩阵变换(矩阵的行列互换)
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print [ [row[col] for row in a] for col in range(len(a[0]))]
输出结果
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
方法二
代码:
def triangles():
L = [1] #定义L为一个只包含一个元素的列表
while True:
yield L #定义为生成器函数
L =[1] + [L[n] + L[n-1] for n in range(1,len(L))] + [1]
n = 0
for t in triangles():
print(t)
n = n + 1
if n == 10:
break
解析
输出:
第一行:L = [1]
len(L) = 1
range(1,1) = [] #此时, L[n-1] for n in range(1,len(L))] 这个for in 不执行
第二行:L = [1] + [L[n] + L[n-1] for n in [] ] + [1]
L = [1] + [1]
L = [1, 1]
len(L) = 2
range(1,2) = [1]
第三行:L = [1] + [L[n] + L[n-1] for n in [1]] + [1]
L = [1] + [ L[1] + L[1-1] ] + [1]
L = [1] + [ L[1] + L[0] ] + [1]
L = [1] + [ 1 + 1] + [1]
L = [1, 2, 1]
以此类推