-
Notifications
You must be signed in to change notification settings - Fork 13
/
timeComplexities.py
124 lines (83 loc) · 2.29 KB
/
timeComplexities.py
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
array = [1, 2, 3, 4, 5]
###### Constant time complexity #######
print('###### Constant time complexity #######')
print(array[0])
###### Linear time complexity #######
print('###### Linear time complexity #######')
for element in array:
print(element)
###### Logarithmic time complexity #######
print('###### Logarithmic time complexity #######')
for index in range(0,len(array),3):
print(array[index])
###### Quadratic time complexity #######
print('###### Quadratic time complexity #######')
for x in array:
for y in array:
print(x,y)
###### Exponential time complexity #######
print('###### Exponential time complexity #######')
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
###### Add vs Multiply #######
arrayA = [1,2,3,4,5,6,7,8,9]
arrayB = [11,12,13,14,15,16,17,18,19]
for a in arrayA:
print(a)
for b in arrayB:
print(b)
for a in arrayA:
for b in arrayB:
print(a,b)
###### Iterative algorithm - finding the biggest number in the array #######
sample1Array = [1,10,45,33,23,45,67,2,3,33,55,11,65,76,34,35,27,99]
def findBiggestNumber(sampleArray):
biggestNumber = sampleArray[0]
for index in range(1,len(sampleArray)):
if sampleArray[index] > biggestNumber:
biggestNumber = sampleArray[index]
print(biggestNumber)
findBiggestNumber(sample1Array)
###### Recursive algorithm - finding the biggest number in the array #######
def findMaxNumRec(sampleArray, n):
if n == 1:
return sampleArray[0]
return max(sampleArray[n-1],findMaxNumRec(sampleArray,n-1))
print(findMaxNumRec(sample1Array,len(sample1Array)))
###### Recursive algorithm multiple calls #######
def f(n):
if n <= 1:
return 1
return f(n-1) + f(n-1)
print(f(3))
###### Quiz Questions #######
def f1(n):
if n <= 0:
return 1
else:
return 1 + f1(n-1)
def f2(n):
if n <= 0:
return 1
else:
return 1 + f2(n-5)
def f3(n):
if n <= 0:
return 1
else:
return 1 + f3(n/5)
def f4(n,m,o):
if n<=0:
print(n,m,o)
else:
f4(n-1,m+1,o)
f4(n-1,m,o+1)
def f5(n):
for i in range(0,n,2):
print(i)
if n<=0:
return 1
else:
return 1 + f5(n-5)