所以我的代码出于某种原因给了我错误:
TypeError: Can't convert 'int' object to str implicitly
这与线路有关:
answer = answer + combination(row, column) + "\t"
这是我的代码:
def combination(n, k):
if k == 0 or k == n:
return 1
return combination(n - 1, k - 1) + combination(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)
答案 0 :(得分:2)
TypeError:无法转换' int'隐含地反对str
在这一行:
answer = answer + combination(row, column) + "\t"
^ ^
|__ str |__ int
combination()
会返回int
,而在Python中则无法执行" str + int"隐式地,所以明确地将它转换为str
:
answer = answer + str(combination(row, column)) + "\t"
您还可以避免使用字符串连接:
answer = '{ans} {comb} \t'.format(ans=answer, comb=combination(row, column))
答案 1 :(得分:0)
独立于修复您当前问题的str()
转换问题,我想触及您的计算Pascal三角形的算法。您的方法独立地计算每一行,忽略计算的上一行为您提供了下一行的步骤。考虑我的(非递归)方法:
def pascals_triangle(rows):
array = []
for row in range(rows):
array.append(1) # both widens the row and initializes the last element
for i in range(row - 1, 0, -1): # fill in the row, right to left
array[i] += array[i - 1] # current computed from previous
print(*array, sep="\t")
在我的系统上将行数从10增加到25,这种方法的速度提高了约400倍。这是由于算法,而不是递归。同样的方法可以递归和快速完成:
def pascals_triangle(rows):
array = [1]
if rows > 1:
array[0:0] = pascals_triangle(rows - 1)
for i in range(rows - 2, 0, -1): # fill in the row, right to left
array[i] += array[i - 1] # current computed from previous
print(*array, sep="\t")
return array # return the last completed row