python 杨辉三角
-
triangle=[]
p=int(input('>>>'))
for i in range(0,p):
if i == 0:
triangle.append([1])
else:
current=[1]
for j in range(0,i-1):
current.append(triangle[i-1][j]+triangle[i-1][j+1])
current.append(1)
triangle.append(current)
print(triangle)
for x in range(0,p):
print(' '*(p-x-1),end=' ')
for c in triangle[x]:
print(c,end=' ')
print()
利用list嵌套存储每一行,利用append,计算一行,附加一行,后续随着高级语法学习,会有占用内存更少的语法实现.
-
triangle=[]
p=int(input('>>>'))
for z in range(0,p):
row=[1]
triangle.append(row)
if z==0:
continue
for m in range(0,len(triangle[z-1])-1):
#for m in range(0,z-1):
row.append(triangle[z-1][m]+triangle[z-1][m+1])
row.append(1)
print(triangle)
for x in range(0,p):
print(' '*(p-1-x),end=' ')
for c in triangle[x]:
print(c,end=' ')
print()利用引用类型存储的是地址,通过改变引用类型的值,间接改变原list
-
p=int(input('>>>'))
oldline=[]
newline=[1]
print(newline)
for z in range(1,p):
oldline=newline.copy()
oldline.append(0)
newline.clear()
for x in range(0,z+1):
newline.append(oldline[x-1]+oldline[x])
print(newline)
随机数模块
-
random.randint(a,b) 返回[a,b]间随机一个整数
-
random.choice(seq) Choose a random element from a non-empty sequence,random.choice(range(5)) random.choice([1,3,5,7])
-
random.randrange(start,stop=None[,step=1]) Choose a random item from range(start,stop[,step])
-
random.shuffle(x,random=None) shuffle list x in place,and return None