Skip to content

Instantly share code, notes, and snippets.

@winny-
Created April 18, 2017 22:38
Show Gist options
  • Save winny-/f84365e64760d4868f108d7105c18c81 to your computer and use it in GitHub Desktop.
Save winny-/f84365e64760d4868f108d7105c18c81 to your computer and use it in GitHub Desktop.
"""
This code is in the public domain.
"""
import unittest
def fib_loop(n):
x, y = 1, 0
for _ in range(n):
y, x = x, x + y
return x
def fib_recursion(n):
def f(m, x, y):
return f(m - 1, x + y, x) if m > 0 else x
return f(n, x=1, y=0)
def fib_generator():
x, y = 1, 0
while True:
yield x
y, x = x, x + y
class FibTest(unittest.TestCase):
expected = [1, 1, 2, 3, 5, 8, 13, 21]
def testFib(self):
for index, n in enumerate(self.expected):
self.assertEqual(fib_loop(index), n)
self.assertEqual(fib_recursion(index), n)
def testGenerator(self):
for actual, n in zip(fib_generator(), self.expected):
self.assertEqual(actual, n)
if __name__ == '__main__':
print(fib_loop(input('gibe number: ')))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment