mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-05-23 00:41:19 -04:00
Change the dir structure slightly
This commit is contained in:
parent
6b6fe21db3
commit
2f4a9638c0
184 changed files with 0 additions and 21 deletions
60
source_code/builtin_structures/fibonacci.py
Executable file
60
source_code/builtin_structures/fibonacci.py
Executable file
|
@ -0,0 +1,60 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
def fib_generator():
|
||||
a, b = 0, 1
|
||||
|
||||
while True:
|
||||
yield b
|
||||
a, b = b, a+b
|
||||
|
||||
|
||||
def fib(n):
|
||||
'''
|
||||
>>> fib(2)
|
||||
1
|
||||
>>> fib(5)
|
||||
5
|
||||
>>> fib(7)
|
||||
13
|
||||
'''
|
||||
if n < 3:
|
||||
return 1
|
||||
|
||||
a, b = 0, 1
|
||||
count = 1
|
||||
|
||||
while count < n:
|
||||
count += 1
|
||||
a, b = b, a+b
|
||||
|
||||
return b
|
||||
|
||||
|
||||
def fib_rec(n):
|
||||
'''
|
||||
>>> fib_rec(2)
|
||||
1
|
||||
>>> fib_rec(5)
|
||||
5
|
||||
>>> fib_rec(7)
|
||||
13
|
||||
'''
|
||||
if n < 3:
|
||||
return 1
|
||||
return fib_rec(n - 1) + fib_rec(n - 2)
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import doctest
|
||||
doctest.testmod()
|
||||
|
||||
fib = fib_generator()
|
||||
print(next(fib))
|
||||
print(next(fib))
|
||||
print(next(fib))
|
||||
print(next(fib))
|
Loading…
Add table
Add a link
Reference in a new issue