I am trying to create a triangle which takes in user inputted values and from the values would like to find the maximum route in these inputs. I intitally asked the question to find the maximum route in this: Finding the Maximum Route in a given input
Code:
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)
The error i get after inputting all my values for triangle:
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
Where is my error in my code? Need some help.. Thanks…
You are probably trying ot get the value of
PrintingList, created inside thetrianglefunction as therowsvariable inside theroutesfunction.For your program to work that way you have to add a return statement in your triangle function – that is, add a
return PrintingListas the last statement there – and store this value when you call the function, and pass the stored value to theroutesfunction – which means, the ending of your program should read something like:That will fix this problem, there may be other issues in the code above.