用列表生成帕斯卡尔三角形
我的作业是用列表来制作帕斯卡三角形。我会接收用户输入的三角形高度,然后从这个高度开始构建三角形。我有一段伪代码,但我不知道如何实现最后的“Else”部分,那里提到要找到“A”的值,它在三角形上面一行,往回一列;还有“B”的值,它在三角形上面一行,列数不变。
这是我的伪代码:
https://i.stack.imgur.com/aFwkT.jpg.谢谢!
代码:
def pascalsTriangle():
height = int(input("Enter height of triangle:"))
t_List = []
for R in t_List(0,height+1):
n_List = []
if R == 0:
n_List = [1]
elif R == 1:
n_List == [1,1]
else:
for C in R:
if C == 0:
n_List.append(1)
elif C == R:
n_List.append(1)
else:
A = t_List()
5 个回答
0
这个应该对你有用:
def my_pattern(n):
tree = [[1]] #first row is always just 1
for x in range(1, n): #for every other row:
m = [1] #it always starts with 1
for y in range(1, x): #for all the others:
m.append(tree[x-1][y-1] + tree[x-1][y]) #work out what the number is
m.append(1) #it always ends in 1
tree.append(m) #add the row on
return tree
0
你可以为这个三角形创建一个列表,里面包含多个列表,每个列表代表三角形的一行。这些行可以通过递归的方式生成。
height = int(input())
def pascal(h, nums): # Height and array of current triangle
if h == 1: # finished!
return nums
next_row = [1]# Start row
# Iterate through the last row
for i in range(len(nums[-1]) - 1):
# Append each item in the last row addded to the item on the right
next_row.append(nums[-1][i] + nums[-1][i + 1])
next_row.append(1) # End row
nums.append(next_row) # Add row to triangle
return pascal (h - 1, nums) # Repeat at next row
# Start the recursion with the top of the triangle
triangle = pascal(height, [[1]])
print triangle
0
你可以创建一个列表的列表。
def pascalsTriangle():
height = int(input("Enter height of triangle: "))
triangle = []
row = []
prev_row = []
for i in xrange(0, height + 1):
row = [j > 0 and j < i - 1 and i > 2 and prev_row[j-1] + prev_row[j] or 1 for j in xrange(0, i)]
prev_row = row
triangle += [row]
return triangle[1:]
比如说:
Enter height of triangle: 5
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
0
def pascal_triangle(height):
if height < 0 : return
# height = 0
T = [[1]]
# loop for the next r = [1:height+1]
for R in range(1, height + 2):
# c == 0
N = [1]
# caculate [1:r) (exclude r itself)
for C in range(1, R):
a = T[R - 1][C - 1]
b = T[R - 1][C]
# c = a + b
N.append(a + b)
# c == r
N.append(1)
T.append(N)
# print each R, from [0, height+1], total row is height+2
for R in T:
# i want to a pyramid, but the last row will
# still have a single leading space
print ' ' * (height - len(R) + 2),
for C in R:
print C,
# new line
print
if __name__ == '__main__':
import sys
pascal_triangle(int(sys.argv[1]))
$ python /tmp/test.py 4
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。
0
from functools import reduce
def pascal (level, acc = None):
if not acc: acc = [[1]]
if level == 1: return acc
acc.append ( [1] + [a + b for a, b in zip (acc [-1], acc [-1] [1:] ) ] + [1] )
return pascal (level - 1, acc)
print (pascal (6) )
当然可以!不过你没有提供具体的内容。请把你想要翻译的StackOverflow内容发给我,我会帮你用简单易懂的语言解释清楚。