-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzad14.py
More file actions
56 lines (47 loc) · 1.16 KB
/
zad14.py
File metadata and controls
56 lines (47 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# Napisz dwie funkcje zwracające n-ty wyraz ciągu
# Fibonacciego. Pierwsza powinna obliczać go iteracyjnie,
# a druga rekurencyjnie. Następnie korzystając z modułu
# time porównaj czas działania obu funkcji w zależności
# od wartości n (n od zera do ok. 30 - 40) i przedstaw je
# na wykresie.
import time
import matplotlib.pyplot as plt
def fibonacciRecursion(n):
if n <= 1:
return n
else:
return(fibonacciRecursion(n-1) + fibonacciRecursion(n-2))
def fibonacciIteration(n):
a = 0
b = 1
c = b
while(n - 1 > 0):
c = a + b
a, b = b, c
n -= 1
return c
n = []
nIterTime = []
nRecuTime = []
for i in range(35):
# print(i)
n.append(i)
startTimeIter = time.time()
fibonacciIteration(i)
endTimeIter = time.time()
timeIter = endTimeIter-startTimeIter
nIterTime.append(timeIter)
startTimeRecu = time.time()
fibonacciRecursion(i)
endTimeRecu = time.time()
timeRecu = endTimeRecu-startTimeRecu
nRecuTime.append(timeRecu)
# print(n)
# print(nIterTime)
# print(nRecuTime)
plt.plot(n, nIterTime, label = "Iteration")
plt.plot(n, nRecuTime, label = "Recursion")
plt.xlabel("n")
plt.ylabel("Time [s]")
plt.legend()
plt.show()