gpt4 book ai didi

python - 帕斯卡三角形 - 类型错误

转载 作者:行者123 更新时间:2023-12-01 03:59:19 26 4
gpt4 key购买 nike

所以我的代码由于某种原因给了我错误:

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)

最佳答案

TypeError: Can't convert 'int' object to str implicitly

在这一行中:

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))

关于python - 帕斯卡三角形 - 类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36896672/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com