Skip to content

Instantly share code, notes, and snippets.

Last active Dec 23, 2015
What would you like to do?
A read-only dictionary, storing fibonacci numbers
# Copyright 2013, Alex Ausch
# Free to use under attribution license:
from import Mapping
except ImportError:
from collections import Mapping
class FibDict(Mapping):
"""A FibDict object stores the Fibonnaci sequence, mapping numbers
to their place in the sequence:
>>> f = FibDict()
>>> f[1]
>>> f[2]
The object generates Fibonnaci numbers as needed. When iterated over,
it yields the Fibonnaci numbers found so far:
>>> f[11]
>>> list(f[11])
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
instance = None
def __new__(cls):
if cls.instance is None:
cls.instance = super(FibDict, cls).__new__(cls)
return cls.instance
def __init__(self):
super(FibDict, self).__init__()
self.inner_dict = {}
self.inner_dict[1] = 0
self.inner_dict[2] = 1
def __len__(self):
return len(self.inner_dict)
def __setitem__(self, key, value):
return self.__getitem__(key) #it's a read-only dict
def __delitem__(self, key):
return self.__getitem__(key) #it's a read-only dict
def __contains__(self, key):
if not key in self.inner_dict:
return key in self.inner_dict
def __iter__(self):
return iter(self.inner_dict.values())
def __getitem__(self,key):
key = int(key)
if key < 1: return False
return self.inner_dict[key]
except KeyError, e:
self.inner_dict[key] = self.__getitem__(key-1) + self.__getitem__(key-2)
return self.inner_dict[key]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment