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:(adsbygoogle = window.adsbygoogle || []).push({});

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!

**Physics Forums | Science Articles, Homework Help, Discussion**

Dismiss Notice

Join Physics Forums Today!

The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

# Cache in python?

**Physics Forums | Science Articles, Homework Help, Discussion**