2016-04-27 45 views
1

所以,我由于某种原因,代码是给我的错误:杨辉三角 - 错误类型

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) 

回答

2

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

无关的str()转换问题,解决您的直接问题,我想谈谈您的算法计算帕斯卡我的三角。你的方法独立地计算每一行,忽略前一行计算给你一个下一步。再看看我(非递归)方法:

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