2012-04-13 18 views
0

私は、ユーザが入力した値を取り込み、その値からこれらの入力で最大のルートを探したい三角形を作成しようとしています。私はintitallyこの中で最大のルートを見つけるために質問を:Finding the Maximum Route in a given inputPythonの入力として三角形を入力する

コード:

def triangle(rows): 
    for rownum in range (rows): 
     PrintingList = list() 
     print ("Row no. %i" % rownum) 
     for iteration in range (rownum): 
      newValue = input("Please enter the %d number:" %iteration) 
      PrintingList.append(int(newValue)) 
      print() 
def routes(rows,current_row=0,start=0): 
    for i,num in enumerate(rows[current_row]): 
     #gets the index and number of each number in the row 
     if abs(i-start) > 1: # Checks if it is within 1 number radius, if not it skips this one. Use if not (0 <= (i-start) < 2) to check in pyramid 
      continue 
     if current_row == len(rows) - 1: # We are iterating through the last row so simply yield the number as it has no children 
      yield [num] 
     else: 
      for child in routes(rows,current_row+1,i): #This is not the last row so get all children of this number and yield them 
       yield [num] + child 


numOfTries = input("Please enter the number of tries:") 
Tries = int(numOfTries) 
for count in range(Tries): 
    numstr= input("Please enter the height:") 
    rows = int(numstr) 
    triangle(rows) 
    routes(triangle) 
    max(routes(triangle),key=sum) 

私は三角形のためにすべての私の値を入力した後、取得エラー:

Traceback (most recent call last): 
    File "C:/Users/HP/Desktop/sa1.py", line 25, in <module> 
    max(routes(triangle),key=sum) 
    File "C:/Users/HP/Desktop/sa1.py", line 10, in routes 
    for i,num in enumerate(rows[current_row]): #gets the index and number of each number in the row 
TypeError: 'function' object is not subscriptable 

私の誤りがあります私のコードで?いくつかの助けが必要..おかげで...あなたが使用している

+0

ルート(三角形)とはどういう意味ですか? –

+0

三角(行)は何も返しません。 – cfedermann

答えて

1

あなたのプログラムがそのように動作するためには、あなたの三角関数にreturnステートメントを追加する必要があります。つまり、そこに最後のステートメントとしてreturn PrintingListを追加し、関数を呼び出すときにこの値を保存し、 、この問題が解決されます上記のコードでは他の問題があるかもしれ

result = triangle(rows) 
routes(result) 
max(routes(triangle),key=sum) 

: - routes機能を意味し、あなたのプログラムのエンディングのようなものをお読みください。

2

routes(triangle) 

triangle名前がroutesを関数の最初の引数rowsとして渡される関数を指します。ファンクション本体では、rows[current_row]は実際にはrowsであるため、エラーが発生します。

あなたがしようとしていることは本当にわかりません。おそらくPrintingListtrianglesに戻し、この結果を関数routesに順番に渡したいと思っていますか?

-3

トレースバックが記載されているように、その25と10行目のように。関数がサブスクリプト化できないというのは、実際には関数にサブスクライブできないということです。ただし、を購読することができます:あなたはおそらくroutes関数内rows変数としてtriangle関数の内部で作成されたPrintingListの値を取得しようとしているotの

String: "x"[2] == "foo" 
Tuple: (2,5,2,7)[3] == 7 
List: [1,2,3,"foo"][3] == "foo" 
Dict: {"a":1, "b":5, "c":5}["a"] == 1 
関連する問題