Created
March 12, 2020 23:25
-
-
Save dbramucci/dbbe7cb43d4b8b43b18093e86b9b407b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Forgets results in between calls | |
# Also, it is nowhere close to as efficient as the Haskell version | |
# i.e. I think this is exponential in time | |
def fibs_gen(): | |
yield 0 | |
yield 1 | |
fib = fibs_gen() | |
fib_tail = fibs_gen() | |
next(fib_tail) | |
for i, j in zip(fib, fib_tail): | |
yield i + j | |
for i, x in enumerate(fibs_gen()): | |
if i >= 100: | |
break | |
print(x) | |
# Psuedo-Infinite List | |
# Remembers middle results between function calls | |
# Uses array, not linked list representation | |
# Not recursive | |
class Fib: | |
_fibs = [0, 1] | |
def __getitem__(self, index): | |
for i in range(len(self._fibs), index + 1): | |
self._fibs.append(self._fibs[i - 1] + self._fibs[i - 2]) | |
return self._fibs[index] | |
fibs = Fib() | |
print(fibs[100]) | |
# Psuedo-Infinite List | |
# Remembers middle results between function calls | |
# Uses array, not linked list representation | |
# Recursive | |
# Closest Python version to the Haskell code | |
class FibRec: | |
_fibs = [0, 1] | |
def __getitem__(self, index): | |
if index >= len(self._fibs): | |
self._fibs.append(self[index - 1] + self[index - 2]) | |
return self._fibs[index] | |
fibs_rec = FibRec() | |
print(fibs_rec[56]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment