2012-04-13 77 views
0

我正嘗試創建一個三角形,它接受用戶輸入的值,並從這些值想要在這些輸入中找到最大路徑。我intitally問的問題找到這個最大路線:Finding the Maximum Route in a given input在Python中輸入三角形作爲輸入

代碼:

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

「路線(三角形)」應該是什麼意思? – 2012-04-13 13:20:31

+0

三角形(行)不返回任何東西。 – cfedermann 2012-04-13 13:21:27

回答

1

你大概OT得到PrintingList值時,triangle函數內部創建爲routes函數內部的rows變量。

爲了讓程序以這種方式工作,您必須在三角函數中添加return語句 - 即將return PrintingList作爲最後一個語句添加 - 並在調用該函數時存儲此值,並將存儲的值到routes功能 - 這意味着,你的計劃結束後應改爲類似:

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

這將解決這個問題,有可能在上面的代碼中的其他問題。

2

您正在使用:

routes(triangle) 

triangle名是指一個功能,它作爲第一個參數rows運作routes通過。在函數體中,rows[current_row]產生錯誤,因爲rows確實是一個函數。

我真的不知道你在做什麼。也許你想從triangles返回PrintingList,並將這個結果依次傳遞給函數routes

-3

由於回溯說明,它在像25和第10行。它是說,該功能不是可以訂閱的,這是真的,你不能訂閱一個功能。您可以訂閱,但是:

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