Skip to content

Instantly share code, notes, and snippets.

@aausch
Last active December 23, 2015 23:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aausch/6707846 to your computer and use it in GitHub Desktop.
Save aausch/6707846 to your computer and use it in GitHub Desktop.
A read-only dictionary, storing fibonacci numbers
# Copyright 2013, Alex Ausch
# Free to use under attribution license: http://creativecommons.org/licenses/by/2.0/ca/
try:
from collections.abc 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]
0
>>> f[2]
1
The object generates Fibonnaci numbers as needed. When iterated over,
it yields the Fibonnaci numbers found so far:
>>> f[11]
55
>>> 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:
self.__getitem__(key)
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
try:
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