如何用python输出杨辉三角
iangles里用到了yield,yield
的作用就是把一个函数变成一个
generator
用python语言输出九九乘法表 杨辉三角 求代码
1、九九乘法表def multiplicationTable():
for i in range(1, 10):
for j in range(1, i):
print "%d * %d = %d\t" % (j, i, j * i),
print "%d * %d = %d\n" % (i, i, i * i),
if __name__ == '__main__':
multiplicationTable()
2、杨辉三角def pascalsTriangle(n):
line = [1]
print "\t" * (n - 1),
print "%d\n" % line[-1],
for i in range(n - 1):
new_line = [1]
for j in range(i):
new_line.append(line[j] line[j 1])
new_line.append(1)
line = new_line
print "\t" * (n - i - 2),
for each in line[:-1]:
print "%d\t\t" % each,
print "%d\n" % line[-1],
if __name__ == '__main__':
pascalsTriangle(7)
新手求教:请问怎样用python 显示杨辉三角,任意输入一个数N,输出一个N 1层的杨辉三角。
试一下:#/usr/bin/python
# coding:utf-8
n = -1
while n n = raw_input("Enter a nonnegative integer >= 0:")
try:
n = int(n)
except:
print "please enter integer!"
n = -1
tmppascal = [0,]* (2 * n 3)
pascal = []
for i in range(n 2):
pascal = [tmppascal[:],]
center = n 1
pascal[1][center] = 1
x = y = 0
for i in range(2, n 2):
if n % 2 == 1:
if i % 2 == 0:
x = 1
y = 2 * n 2
else:
x = 2
y = 2 * n 1
else:
if i % 2 == 1:
x = 1
y = 2 * n 2
else:
x = 2
y = 2 * n 1
for j in range(x, y, 2):
pascal[i][j] = pascal[i - 1][j - 1] pascal[i - 1][j 1]
if n % 2 == 0:
max = pascal[n 1][center]
else:
max = pascal[n 1][center - 1]
maxlen = len(str(max))
for row in pascal[1:]:
for col in row[1:-1]:
if col == 0:
col = ""
fm = '{0: ^' str(maxlen) '}'
print fm.format(col),
python新手 杨辉三角
1) enumerate(iterable) 是对一个可遍历对象进行遍历时添加遍历的方. 例如:>>> alst = ['d' % x*2 for x in range(7, 3, -1)]
>>> alst
['0707', '0606', '0505', '0404']
>>> for i, item in enumerate(alst):
... print i, item
...
0 0707
1 0606
2 0505
3 0404
>>>
2) while True: 进入持续; 通常在循环体内有判断逻辑, 当满足条件时 break 或 return
如何用Python实现杨辉三角和心
方法
ef printlove(start,length,midnumber=0,flag=31):
for i in range(31):
if istart length-1 and i<15-(midnumber-1)/2 or i>15 (midnumber-1)/2 and i<31-start-length or i> 30-start or i==flag:
print " ",
else:
print "*",
print ""
for i in range(16):
if i ==0:
printlove(4,3)
elif i==1:
printlove(1,9)
elif i>=2 and i<=5:
printlove(0,i 10)
elif i==6:
printlove(1,7,7,15)
elif i>=7 and i<=8:
printlove(i-5,6,5-(i-7)*2)
elif i==9:
printlove(5,6,1)
elif i==10:
printlove(8,6,1)
elif i==15:
printlove(15,1,1)
else:
printlove(i-1,16-i,1)
版权声明:本站所有文章皆为原创,欢迎转载或转发,请保留网站地址和作者信息。