IE2108 Tutorial 04
IE2108 Tutorial 04
1. The algorithm for finding the maximum element of an array is shown as follows:
3. Solve the recurrence relation ssing the method of backward substitutions to compute the
value for 𝑎𝑛 : 𝑎𝑛 = 𝑎𝑛−1 + 3, where 𝑎1 = 2.
4. Determine the complexity of the following recursive function. (You may assume that n = 2k
in this case).
𝑛
𝑇(𝑛) = 2𝑇 ( ) + 𝑐𝑛 if n > 1
2
𝑇(𝑛) = 1 if n = 1
def fact(n):
if n == 0:
print("n = ", n)
return 1
else:
print("n = ", n)
return n*fact(n-1)
n = int(input("Enter n: "))
print("factorial({0}) = {1}".format(n, fact(n)))
class Stack:
def __init__(self):
Ver 20240125
An 3 an 2
an-1 + =
1.
=
,
an -
1
=
An -
1 -
1 + 3
=
an -
2 + 3
an =
(an - 2
+ 3) + 3
=
(9n -
3
+ 3) + 3 + 3 =
an 3
-
+ 3x3
=
(an -
y
+ 3) + 3 + 3 + 3 = an -
4 + 3X4
An -k
=
+ (3xk)
=
An + 3(n 1)
(n
-
- -
1)
When A[O] a , 3
the
largest this statement will not be executed
. + 3n
=
is element the
in
array
-
=
3n -
1
XX
Worst case Scenario currentMax =
Account] will be executed is n-1.
ak =
29k + k when k =
1 a =
-
1 ,
ak -1 =
29k -
2 + (k -
11 k =
2
,
az = 2(1) + 2 = 4 T[n] =
2+ (E) + Ch
ak -
2
=
29k -
z
+ (k -
2) k = 3
, az =
2(4) + 3 = 11 =
2[2T(E = 2) + x(z)] + c
ak -
(k 2)
-
=
29k 1 -
-
2) -
1
+ (k -
k+ 2) k =
4
,
a4
=
2)(1) + 4 = 2) =
22 T(f) + ((n) + c
az
=
29 , + 2 k = 5
,
95 =
2(26) + 5 =
57 = 22 + (4) + 2
= 2 + 2 =
4
93 = 212 + 3 =
22(2T(8) +
c(f)] + 2
=
2(43 + 3 = 11 =
23T() + 3
My =
293 + 4 =
2 T(Ex) +
12
=
2(11) +4 = 46
let n = 2k
Ign :
k1g2 = 1
T(m)
=
n T (1) +
<n(g(n)
0(u
Ign)
=
n =
4
,
4 X fact (3)
n = 3
3x fact (2)
n = 2
,
2x fact (1)
n =
1 1x fact (0)
n = 0 return 1
,
self.items = []
def pop(self):
if not self.empty():
return self.items.pop()
else:
raise IndexError("Stack is empty")
def top(self):
if not self.empty():
return self.items[-1]
else:
raise IndexError("Stack is empty")
def empty(self):
return len(self.items) == 0
Show the output value if a value is returned from the operation and list the content of
the stack after each operation.
print(S.pop(), S.items) -
5 [8]
print(S.push(2), S.items) Now e [8, 27
print(S.top(), S.items) 2 [8, 27
print(S.pop(), S.items) 2 [8]
print(S.empty(), S.items) FALSE [8]
print(S.top(), S.items) 8 [8]
7. Suppose that Q is an ADT queue. Define the queue functions similar to those of
Question 6. List the content of the queue after each operation and show the output
value if a value is returned from the operation.
Q.enqueue(-5) none 8 .
-
5
Q.dequeue( ) g -
Q.enqueue(2) none -
5 2
,
Q.front( ) -
5 -
5, 2
Q.dequeue( ) -
5 2
Q.empty( ) FALSE 2
Q.front( ) 2 2
Ver 20240125
Python Practice (This part is for your self-study. You can use the Python interpreter to
check your predicted results)
class Node:
# constructor
def __init__(self, data = None, next = None):
self.data = data
self.next = next
Ver 20240125