I am a Python newbie.
The following was a beginner level problem at codechef.com Link to problem
Problem Text:
Let's consider a triangle of numbers in which a number appears in the first line, two numbers appear in the second line, three in the third line, etc. Develop a program which will compute the largest of the sums of numbers that appear on the paths starting from the top towards the base, so that:
- on each path the next number is located on the row below, more precisely either directly below or below and one place to the right;
- the number of rows is strictly positive, but less than 100
- all numbers are positive integers between O and 99.
Input
In the first line integer n - the number of test cases (equal to about 1000). Then n test cases follow. Each test case starts with the number of lines which is followed by their content.
Output
For each test case write the determined value in a separate line.
The following is my code:
tempij=[]
s=0
def solve(i,j,ll):
global s
s=0
tempij=[]
if i==len(ll):
return 0
elif (i,j) in tempij:
return s
else:
tempij.append((i,j))
t1=solve(i+1,j,ll)
t2=solve(i+1,j+1,ll)
t=max(t1,t2)+ll[i][j]
s=t
return t
t=int(input())
ll=[]
for k in range(t):
ll=[]
n=int(input())
for i in range(n):
lst=[]
text=input().split()
for j in range(len(text)):
lst.append(int(text[j]))
ll.append(lst)
print(solve(0,0,ll))
Problem with this code:
I have tried to implement Recursion with Memoization in accordance with their editorial on this problem. Link to editorial
Code explained (Relevant part of editorial):
(I am using tempij for caching in the code above. Something similar to SO question: SO question about memoization)
While it works for the test cases given as example, it seems to be exceeding the time limit for other test cases.
My question: How do I improve this code? Or is there a better way?