2016-04-27 7 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 + 1 INT」を行うことができないので、明示的にstrに変換します

answer = answer + str(combination(row, column)) + "\t" 

あなたはまた、一緒に何かを持つために、文字列の連結を回避することができる。

answer = '{ans} {comb} \t'.format(ans=answer, comb=combination(row, column)) 
0

すぐに問題を解決するstr()変換の問題とは関係なく、私はPascaを計算するためのアルゴリズムに触れたいと思います私は三角形です。あなたのアプローチは、計算された前の行があなたに次のステップを与えることを無視して、すべての行を独立して計算します。私の(非再帰的)なアプローチを考えてみましょう:

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 
関連する問題