显示全 1 的帕斯卡三角形
Pascals Triangle Displaying All 1s
我正在尝试制作帕斯卡三角形,但我得到的是全 1 的三角形。有人可以告诉我我做错了什么吗?
def pascals(row, column):
if column == 0:
return 1
if row == 0:
return 1
if row < 0:
return 0
if column < 0:
return 0
if column > row:
return 0
if column == row:
return 1
else:
return pascals(row - 1, column -1 + pascals(row - 1, column))
# generate the first 10 rows of Pascal's Triangle
for row in range(10):
print('{: ^45}'.format(' '.join(str(pascals(row, col)) for col in range(row+1)))
应该是pascals(row - 1, column - 1) + pascals(row - 1, column)
不是pascals(row - 1, column - 1 + pascals(row - 1, column))
代码应该是:
def pascals(row, column):
if column == 0:
return 1
if row == 0:
return 1
if row < 0:
return 0
if column < 0:
return 0
if column > row:
return 0
if column == row:
return 1
else:
return pascals(row - 1, column - 1) + pascals(row - 1, column) # Your brackets should be like this
# generate the first 10 rows of Pascal's Triangle
for row in range(10):
print('{: ^45}'.format(' '.join(str(pascals(row, col)) for col in range(row+1)))) # you left out one bracket here
现在的输出是:
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
我正在尝试制作帕斯卡三角形,但我得到的是全 1 的三角形。有人可以告诉我我做错了什么吗?
def pascals(row, column):
if column == 0:
return 1
if row == 0:
return 1
if row < 0:
return 0
if column < 0:
return 0
if column > row:
return 0
if column == row:
return 1
else:
return pascals(row - 1, column -1 + pascals(row - 1, column))
# generate the first 10 rows of Pascal's Triangle
for row in range(10):
print('{: ^45}'.format(' '.join(str(pascals(row, col)) for col in range(row+1)))
应该是pascals(row - 1, column - 1) + pascals(row - 1, column)
不是pascals(row - 1, column - 1 + pascals(row - 1, column))
代码应该是:
def pascals(row, column):
if column == 0:
return 1
if row == 0:
return 1
if row < 0:
return 0
if column < 0:
return 0
if column > row:
return 0
if column == row:
return 1
else:
return pascals(row - 1, column - 1) + pascals(row - 1, column) # Your brackets should be like this
# generate the first 10 rows of Pascal's Triangle
for row in range(10):
print('{: ^45}'.format(' '.join(str(pascals(row, col)) for col in range(row+1)))) # you left out one bracket here
现在的输出是:
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