I've wrote the code for Project Euler #15 and it runs amazingly fast. I know I can write it using binomials but I wanted to calculate by brute force as if I do not know Binomials. But I think it must be taking huge amount of memory so I want to know how I can reduce amount of memory used by program. I've tried to reduce elements in the Dictionary as much as possible but I cannot think of any other thing.
import time
st = time.clock()
results = {}
def routes(a, b):
if a > b:
a, b = b, a
if a == 0:
return 1
if a == b:
if str([a - 1, b]) in results:
return 2 * results[str([a - 1, b])]
else:
part1 = routes(a - 1, b)
results[str([a - 1, b])] = part1
return 2 * part1
if str([a - 1, b]) in results:
part1 = results[str([a - 1, b])]
else:
part1 = routes(a - 1, b)
results[str([a - 1, b])] = part1
if str([a, b - 1]) in results:
part2 = results[str([a, b - 1])]
else:
part2 = routes(a, b - 1)
results[str([a, b - 1])] = part2
return part1 + part2
number = int(input("Enter n : "))
#print((routes(20, 20)))
print((routes(number, number)))
#print((results))
print((len(results)))
print(("Time took : ", time.clock() - st))
Output 1:
Enter n : 20 Answer = 137846528820 Number of elements in hashtable/dictionary are 229 Time took : 0.002663 seconds.
Output 2:
Enter n : 480 Answer = 250892214537448775747234101104975594366453286042769782121222122282812207368859289614865150179674097028772541144903685677912632260432728444419421872981795600499773664936037617507243883516784270458848737326769427370361260166492752950426905484595009507753796738842521345046644373977709359600 Number of elements in hashtable/dictionary are 115919 Time took : 0.483901 seconds.