Skip to content

Instantly share code, notes, and snippets.

@ldmoray
Last active August 12, 2016 19:36
Show Gist options
  • Save ldmoray/2459b5bc54fe0f626bb60c1b20abbda9 to your computer and use it in GitHub Desktop.
Save ldmoray/2459b5bc54fe0f626bb60c1b20abbda9 to your computer and use it in GitHub Desktop.
class DynamicFib:
def __init__(self):
self.memo = {0: 0, 1: 1}
def fib(self, n):
if n not in self.memo:
self.memo[n] = self.fib(n-1) + self.fib(n-2)
return self.memo[n]
def slow_fib(n):
if n <= 1:
return n
return slow_fib(n-1) + slow_fib(n-2)
fib = DynamicFib()
fib.fib(30) # 57 microseconds wall time
slow_fib(30) # 434 milliseconds wall time
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment