Skip to content
Snippets Groups Projects
Commit 05f1dab1 authored by nilsl99's avatar nilsl99
Browse files

Added fib5

parent 4d614c78
Branches
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
## OOP Homework 05
### Exercise 1
Dilay Hamaykaya, Nils Liebreich
%% Cell type:code id: tags:
``` python
from functools import cache
```
%% Cell type:code id: tags:
``` python
def fib1(n):
if n <= 1:
return 1
else:
return fib1(n-1) + fib1(n-2)
```
%% Cell type:code id: tags:
``` python
@cache
def fib2(n):
if n <= 1:
return 1
else:
return fib2(n-1) + fib2(n-2)
```
%% Cell type:code id: tags:
``` python
def fib3(n):
fibonacci = [1]*(n+1)
for i in range(2, n+1):
fibonacci[i] = fibonacci[i-1] + fibonacci[i-2]
return fibonacci[n]
```
%% Cell type:code id: tags:
``` python
def fib4(n):
a = b = 1
while n > 0:
a, b = a+b, a
n -= 1
return b
```
%% Cell type:code id: tags:
``` python
answers = {0: 1, 1: 1}
def fib5(n):
if not n in answers:
answers[n] = fib5(n-1) + fib5(n-2)
return answers[n]
```
%% Cell type:code id: tags:
``` python
%timeit fib1(35)
```
%% Output
3.06 s ± 90.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
2.55 s ± 52.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%% Cell type:code id: tags:
``` python
%timeit fib2(35)
```
%% Output
62.2 ns ± 1.44 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)
57.6 ns ± 0.131 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)
%% Cell type:code id: tags:
``` python
%timeit fib3(35)
```
%% Output
4.09 µs ± 193 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
3.37 µs ± 82.7 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
%% Cell type:code id: tags:
``` python
%timeit fib4(35)
```
%% Output
2.76 µs ± 74.1 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
2.2 µs ± 75.1 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
%% Cell type:code id: tags:
``` python
%timeit fib5(35)
```
%% Output
103 ns ± 0.943 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment