Skip to content

Instantly share code, notes, and snippets.

@andrewpatt24
Created July 12, 2016 13:11
Show Gist options
  • Save andrewpatt24/51d3a77cde41e0ea3eab539dc6125518 to your computer and use it in GitHub Desktop.
Save andrewpatt24/51d3a77cde41e0ea3eab539dc6125518 to your computer and use it in GitHub Desktop.
Fibonacci with memory - asked for it in a job application
class memstate:
"""
Takes a function with input:int and output:int
creates memory
"""
def __init__(self,func):
self.func=func
self.memory = {}
def __call__(self,inp):
if inp in self.memory.keys():
print "using memory for "+str(inp)
return self.memory[inp]
else:
self.memory[inp] = self.func(inp)
return self.memory[inp]
@memstate
def fibonacci(i):
"""
Returns fibonacci number number at point i in the recursion
two straight cases
i=0 -> 0
i=1 -> 1
recursive case
i > 1 -> i(x) = i(x-1) + i(x-2)
"""
i0=0
i1=1
if i==0:
return i0
elif i==1:
return i1
else:
for j in xrange(i-1):
i2 = i1+i0
i0=i1
i1=i2
return i2
if __name__ == '__main__':
for i in [0,1,2,3,4,5,6,7,8,8]:
print fibonacci(i)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment