2012-04-13 45 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