- #1
R.Harmon
- 24
- 0
Hey, I decided to start learning python so I downloaded it yesterday and decided to try and make a simple program to produce the Fibonacci series. I managed to do it using a function similar to that on wikibooks:
def fib(n):
if n < 2:
return n
else:
return fib(n - 1) + fib(n - 2)
However, beneath that is a version with cache, where the code is:
def fib(n):
cache = {0: 0, 1: 1}
def xfib(n):
if n not in cache:
cache[n] = xfib(n-1) + xfib(n-2)
return cache[n]
assert n >= 0
return xfib(n)
I tested both these and found the 2nd is far quicker to produce the series, but I don't really understand why, mainly because I can't seem to work out what the line "cache = {0: 0, 1: 1}" is doing, so I was wondering if anyone knows what this piece of code means, and what its telling the program to do subsequently? Hope that's clear, thanks for any help!
def fib(n):
if n < 2:
return n
else:
return fib(n - 1) + fib(n - 2)
However, beneath that is a version with cache, where the code is:
def fib(n):
cache = {0: 0, 1: 1}
def xfib(n):
if n not in cache:
cache[n] = xfib(n-1) + xfib(n-2)
return cache[n]
assert n >= 0
return xfib(n)
I tested both these and found the 2nd is far quicker to produce the series, but I don't really understand why, mainly because I can't seem to work out what the line "cache = {0: 0, 1: 1}" is doing, so I was wondering if anyone knows what this piece of code means, and what its telling the program to do subsequently? Hope that's clear, thanks for any help!