我正在上我的第一堂编程课,我对如何完成这段代码有点迷茫。我正在尝试构建具有 n 行的帕斯卡三角形。我得到了要打印的行,每行都在自己的行上,但是我无法将它们格式化为三角形。以下是我到目前为止所得到的。提前致谢!
def print_pascal_triangle(n):
# problem0_pascal.pascal_triangle(n) provides the rows in a list of lists
rows = problem0_pascal.pascal_triangle(n)
# Now print the rows, one by one, CALLING digits_in_biggest_number
# and print_row as appropriate.
for k in range(len(rows)):
spaces = digits_in_biggest_number(rows[k])
print_row(rows[k], spaces)
def digits_in_biggest_number(row):
"""
Returns the number of digits in the biggest number in the
given list of numbers.
"""
largest = 0
for k in range(len(row)):
if row[k] > largest:
largest = row[k]
digits = int(math.log10(largest)) + 1
return digits
def print_row(numbers, spaces_per_number):
"""
Prints the numbers in the given list of numbers.
Each number is printed using the given number of spaces, except
for the first number (1) which is printed with a single space.
"""
line = ''
for k in range(len(numbers)):
line += str(numbers[k]) + (spaces_per_number * ' ')
print(line)