Python 帕斯卡三角递归程序

Python Pascal's Triangle Recursion Program

我正在尝试编写一个程序来打印帕斯卡三角形。这是我的代码:

def combination(n, k):
    if k == 0 or k == n:
        return str(1)
    else:
        return combination(str(n-1, k-1)) + combination(str(n-1,k))

def pascals_triangle(rows):
    for row in range(rows):
        answer = ""
        for column in range(row + 1):
            answer = answer + combination(row, column) + "\t"
        print(answer)

pascals_triangle(10)

这是我的任务(这是一项作业):

# To complete this assignment, replace the code for the
# combination function with the proper definition.

def combination(n, k):
    return "C(" + str(n) + "," + str(k) + ")"

def pascals_triangle(rows):
    for row in range(rows):
        answer = ""
        for column in range(row + 1):
            answer = answer + combination(row, column) + "\t"
        print(answer)

pascals_triangle(10)

应该打印这个:

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

我知道问题出在组合函数中,但每次我尝试修复某些问题时都会出现更多错误。这目前让我得到这个错误:

TypeError: str() 参数 2 必须是 str,而不是 int

我是一个初学者,所以我可能还遗漏了一些其他的东西。我可以帮助修复此错误以及我遗漏的任何其他内容吗?

对于每个新级别,在每一侧插入一个,并将上述级别的每一对的总和插入中间条目。

t = [[1]]
for _ in range(10):
   level = [1]
   for ii in range(len(t[-1]) - 1):
      level += [t[-1][ii] + t[-1][ii+1]]
   level += [1]
   t.append(level)

for level in t: print level

我真的不确定你写的代码是为了什么。我试过了,但我不明白你想用这个组合函数实现什么。

def combination(n, k):
    if k == 0 or k == n:
        return 1
    else:
        return combination(n-1, k-1) + combination(n-1,k)

def pascals_triangle(rows):
    for row in range(rows):
        answer = 0
        for column in range(row + 1):
            answer = answer + combination(row, column)
        print(answer)

pascals_triangle(10)

你的直接问题是这一行:

return combination(str(n-1, k-1)) + combination(str(n-1,k))

假设您想保留大部分现有逻辑,最简单的解决方法是:

return str(int(combination(n - 1, k - 1)) + int(combination(n - 1, k)))

完整代码:

def combination(n, k):
    if k == 0 or k == n:
        return str(1)
    else:
        return str(int(combination(n - 1, k - 1)) + int(combination(n - 1, k)))

def pascals_triangle(rows):
    for row in range(rows):
        answer = ""

        for column in range(row + 1):
            answer += combination(row, column) + " "

        print(answer)

pascals_triangle(10)

输出

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 

更好的方法是认识到您不需要递归,也不需要 combination() 函数,而是重新计算 从右到左 :

def pascals_triangle(rows):
    answer = []

    for row in range(rows):
        answer.append(1)  # both widen the row and initialize last element

        for i in range(row - 1, 0, -1):  # fill in the row, right to left
            answer[i] += answer[i - 1]  # current computed from previous

        print(*answer)

输出

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