mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-05-02 06:46:18 -04:00
reorganize dir
Signed-off-by: Mia Steinkirch <mia.steinkirch@gmail.com>
This commit is contained in:
parent
1b6f705e7c
commit
a8e71c50db
276 changed files with 23954 additions and 0 deletions
36
other_resources/interview_cake/math/fib.py
Normal file
36
other_resources/interview_cake/math/fib.py
Normal file
|
@ -0,0 +1,36 @@
|
|||
#!/bin/python
|
||||
|
||||
"""
|
||||
Write a function fib() that takes an integer nn and returns the nnth Fibonacci number.
|
||||
"""
|
||||
|
||||
# this is O(2^n)
|
||||
def fib(n):
|
||||
if n in [1, 0]:
|
||||
return n
|
||||
return fib(n - 1) + fib(n - 2)
|
||||
|
||||
|
||||
print fib(10)
|
||||
|
||||
|
||||
# this is O(n)
|
||||
def fib(n):
|
||||
if n < 0:
|
||||
raise ValueError('Index was negative. No such thing as a '
|
||||
'negative index in a series.')
|
||||
elif n in [0, 1]:
|
||||
return n
|
||||
|
||||
prev_prev = 0 # 0th fibonacci
|
||||
prev = 1 # 1st fibonacci
|
||||
|
||||
for _ in range(n - 1):
|
||||
current = prev + prev_prev
|
||||
prev_prev = prev
|
||||
prev = current
|
||||
|
||||
return current
|
||||
|
||||
|
||||
print fib(10)
|
Loading…
Add table
Add a link
Reference in a new issue