Skip to content

Instantly share code, notes, and snippets.

@dcolish
Created October 27, 2010 02:35
Show Gist options
  • Save dcolish/648306 to your computer and use it in GitHub Desktop.
Save dcolish/648306 to your computer and use it in GitHub Desktop.
Lazy evaluation example using python iterators
from itertools import takewhile
from math import sqrt
class Fib(object):
def __init__(self):
self.i = 2
self.items = [0, 1]
self.n = 0
self.n_1 = 1
def __contains__(self, item):
if item in self.items:
return True
else:
self.items += list(takewhile(lambda x: x <= item, self))
self._rollback()
return self.items[-1]
def __getitem__(self, key):
if key < self.i:
return self.items[key]
elif isinstance(key, slice):
self.items += list(takewhile(
lambda x: self.i <= key.stop + 1, self))
self._rollback()
return self.items[key]
else:
self.items += list(takewhile(lambda x: self.i <= key + 1, self))
self._rollback()
return self.items[-1]
def __iter__(self):
return self
def next(self):
next = self.n + self.n_1
self.n = self.n_1
self.n_1 = next
self.i += 1
return next
def _rollback(self):
"""
When iteration gets stopped by takewhile we've gone one too far
so it needs to be backed up one
"""
self.n = self.items[-2]
self.n_1 = self.items[-1]
self.i -= 1
meh = Fib()
print meh[0]
print meh[10]
print meh[11:14]
sq5 = sqrt(5)
pheta = (1 + sq5) / 2
def closed_fib(n):
return (((pheta ** n) - ((-1 / pheta) ** n))) / sq5
print closed_fib(600)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment