Problem Set
Problem Set
Problem Set I
Exercise 1:
Write an algorithm that reads three integers a, b, and c and determines the maximum
and minimum values among these three numbers. Translate this algorithm into Python.
1
Algorithms II Problem Set I
Correction
Algorithm
Require: Three integers a, b, and c
Ensure: Maximum and minimum values
Read integers a, b, and c
Initialize max_val = a
if b > max_val then
max_val = b
end if
if c > max_val then
max_val = c
end if
Initialize min_val = a
if b < min_val then
min_val = b
end if
if c < min_val then
min_val = c
end if
Output max_val and min_val
Python Implementation
6 # Find maximum
7 max_val = a
8 if b > max_val :
9 max_val = b
10 if c > max_val :
11 max_val = c
12
13 # Find minimum
14 min_val = a
15 if b < min_val :
16 min_val = b
17 if c < min_val :
18 min_val = c
19
20 # Output results
21 print ( f " Maximum : { max_val } " )
22 print ( f " Minimum : { min_val } " )
23
2
Algorithms II Problem Set I
Exercise 2:
Write an algorithm and its Python implementation to calculate:
3
Algorithms II Problem Set I
Correction
1. Power Calculation (xn )
Require: A real number x and a positive integer n
Ensure: Result of xn
Read x and n
Initialize result = 1
for i = 1 to n do
result = result × x
end for
Output result
1 def power (x , n ) :
2 result = 1
3 for _ in range ( n ) :
4 result *= x
5 return result
6
7 x = float ( input ( " Enter base ( x ) : " ) )
8 n = int ( input ( " Enter exponent ( n ) : " ) )
9 print ( f " { x }^{ n } = { power (x , n ) } " )
Listing 2: Power Calculation
2. Factorial Calculation
Require: A positive integer n
Ensure: Factorial of n
Read n
Initialize factorial = 1
for i = 1 to n do
factorial = factorial × i
end for
Output factorial
1 def factorial ( n ) :
2 result = 1
3 for i in range (1 , n + 1) :
4 result *= i
5 return result
6
7 n = int ( input ( " Enter a positive integer for factorial : " ) )
8 print ( f " { n }! = { factorial ( n ) } " )
9
4
Algorithms II Problem Set I
Correction
Require: A positive integer n
Ensure: Sum S = 1 + 2 + · · · + n
Read n
Initialize sum = 0
for i = 1 to n do
sum = sum + i
end for
Output sum
1 def su m _nat ur al_n umbe rs ( n ) :
2 return n * ( n + 1) // 2 # Using formula for efficiency
3
5
Algorithms II Problem Set I
Exercise 3:
Write algorithms and Python programs to calculate the value of the following expressions:
2. B = 1 + 1
1+2
+ 1
1+2+3
+ ... + 1
1+2+3+...+N
, where N ≥ 2
6
Algorithms II Problem Set I
Correction
1. Product A
Require: An integer N ≥ 2
Ensure: Product A
Read N
Initialize product = 1
for k = 2 to N do
sum_k = k(k+1)2
{Triangular number formula}
product = product × sum_k
end for
Output product
1 def ca l cula te _pro duct _A ( N ) :
2 product = 1
3 for k in range (2 , N + 1) :
4 sum_k = k * ( k + 1) // 2 # Triangular number
5 product *= sum_k
6 return product
7
8 N = int ( input ( " Enter N ( 2) : " ) )
9 if N < 2:
10 print ( " Error : N must be 2")
11 else :
12 print ( f " Product A = { cal c u la t e_ p ro d u ct _ A ( N ) } " )
13
2. Sum B
Require: A positive integer n
Ensure: Sum B
Read n
Initialize sum_B = 0
for i = 1 to n do
denominator = i(i+1)
2
{Triangular number}
sum_B = sum_B + denominator
1
end for
Output sum_B
1 def calculate_sum_B ( n ) :
2 sum_B = 0.0
3 for i in range (1 , n + 1) :
4 denominator = i * ( i + 1) // 2 # Triangular number
5 sum_B += 1 / denominator
6 return sum_B
7
8 n = int ( input ( " Enter n ( positive integer ) : " ) )
9 if n < 1:
10 print ( " Error : n must be 1")
11 else :
12 print ( f " Sum B = { calculate_sum_B ( n ) :.6 f } " )
13
Exercise 4:
Write an algorithm to determine all divisors of an integer N entered by the user. Translate
this algorithm into Python.
8
Algorithms II Problem Set I
Correction
Algorithm
Require: An integer N
Ensure: List of all positive divisors of |N | (excluding 0)
Read N
Initialize Nabs = |N |
Create empty list divisors
for i = 1 to Nabs do
if Nabs mod i = 0 then
Append i to divisors
end if
end for
Output divisors
Python Implementation
1 def find_divisors ( n ) :
2 n_abs = abs ( n )
3 divisors = []
4 for i in range (1 , n_abs + 1) :
5 if n_abs % i == 0:
6 divisors . append ( i )
7 return divisors
8
9 try :
10 N = int ( input ( " Enter an integer : " ) )
11 result = find_divisors ( N )
12 print ( f " Divisors of { N }: { result } " )
13 except ValueError :
14 print ( " Invalid input . Please enter an integer . " )
15
9
Algorithms II Problem Set I
Exercise 5:
Write an algorithm that takes a positive integer as input and verifies whether this number
is prime or not. Translate this algorithm into Python
Correction
Algorithm
Require: A positive integer N
Ensure: Boolean result: N is prime or not
Read N
if N ≤ 1 then
Output "Not prime"
return
end if
if N = 2 then
Output "Prime"
return
end if
if N mod 2 = 0 then
Output "Not prime"
return
end if
Initialize is_prime
√ = True
for i = 3 to N step 2 do
if N mod i = 0 then
is_prime = False
end if
end for
if is_prime then
Output "Prime"
else
Output "Not prime"
end if
Python Implementation
10
Algorithms II Problem Set I
Correction
1 import math
2
3 def is_prime ( n ) :
4 if n <= 1:
5 return False
6 if n == 2:
7 return True
8 if n % 2 == 0:
9 return False
10 for i in range (3 , math . isqrt ( n ) + 1 , 2) :
11 if n % i == 0:
12 return False
13 return True
14
15 try :
16 N = int ( input ( " Enter a positive integer : " ) )
17 if is_prime ( N ) :
18 print ( f " { N } is a prime number . " )
19 else :
20 print ( f " { N } is not a prime number . " )
21 except ValueError :
22 print ( " Invalid input . Please enter an integer . " )
23
11
Algorithms II Problem Set I
Exercise 6:
Write an algorithm to calculate the sum of all odd numbers between two values N and
M (1 ≤ N < M ). Translate this algorithm into Python.
12
Algorithms II Problem Set I
Correction
Algorithm
Require: Two integers N and M such that 1 ≤ N < M
Ensure: Sum of all odd numbers in the range [N, M ]
Read N and M
if N ≥ M then
Output "Error: N must be less than M"
return
end if
Initialize sum_odds = 0
for i = N to M do
if i mod 2 = 1 then
sum_odds = sum_odds + i
end if
end for
Output sum_odds
Python Implementation
1 def sum_odd_numbers (N , M ) :
2 if N >= M :
3 return " Error : N must be less than M "
4 total = 0
5 for num in range (N , M + 1) :
6 if num % 2 == 1:
7 total += num
8 return total
9
10 try :
11 N = int ( input ( " Enter N (1 N < M): "))
12 M = int ( input ( " Enter M ( M > N ) : " ) )
13 result = sum_odd_numbers (N , M )
14 print ( f " Sum of odd numbers between { N } and { M }: { result } " )
15 except ValueError :
16 print ( " Invalid input . Please enter integers . " )
17
13
Algorithms II Problem Set I
Exercise 7:
Write an algorithm that asks the user for the lengths of the sides of a triangle (lengths are
positive integers) and determines whether this triangle is a right triangle or not. Translate
this algorithm into Python.
14
Algorithms II Problem Set I
Correction
Algorithm
Require: Three positive integers a, b, and c
Ensure: Boolean result: Triangle is right-angled or not
Read a, b, c
if a ≤ 0 OR b ≤ 0 OR c ≤ 0 then
Output "Invalid input: All sides must be positive."
return
end if
Sort a, b, c such that a ≤ b ≤ c
if a + b ≤ c then
Output "Invalid triangle: Triangle inequality violated."
return
end if
if a2 + b2 = c2 then
Output "Right-angled triangle"
else
Output "Not a right-angled triangle"
end if
Python Implementation
17 if a + b <= c :
18 print ( " Invalid triangle : Triangle inequality violated . " )
19 return
20
21 if a **2 + b **2 == c **2:
22 print ( " This is a right - angled triangle . " )
23 else :
24 print ( " This is not a right - angled triangle . " )
25
26 is_r ight_triangle ()
27
15
Algorithms II Problem Set I
Exercise 8:
Write an algorithm to convert a binary number N to decimal (The values 0 and 1 entered
by the user are stored as characters ’0’ and ’1’, and the binary word N is stored in a
string). Example execution:
16
Algorithms II Problem Set I
Correction
Algorithm
Require: Number of bits N and N binary digits from MSB to LSB
Ensure: Decimal value of the binary number
Read N
Initialize decimal = 0
for i = 0 to N − 1 do
Read bit bi (either ’0’ or ’1’)
decimal = decimal × 2 + int(bi )
end for
Output decimal
Python Implementation
17
Algorithms II Problem Set I
Exercise 9:
Write an algorithm for the input of an integer n, the calculation and display of the n-th
term of the sequence (Un ) defined as follows:
U0 = 2
U1 = 3
Un+2 = 32 Un+1 − 14 Un
18
Algorithms II Problem Set I
Correction
Algorithm
Require: A non-negative integer n
Ensure: The n-th term of the sequence Un
Read n
if n = 0 then
Output 2
else if n = 1 then
Output 3
else
Initialize U0 = 2, U1 = 3
for i = 2 to n do
U2 = 32 · U1 − 41 · U0
Update U0 = U1 , U1 = U2
end for
Output U2
end if
Python Implementation
1 def c o m pu te _ s eq ue nc e_ te rm ( n ) :
2 if n < 0:
3 return " Error : n must be a non - negative integer . "
4 if n == 0:
5 return 2.0
6 if n == 1:
7 return 3.0
8
9 u0 , u1 = 2.0 , 3.0
10 for _ in range (2 , n + 1) :
11 u2 = (2/3) * u1 - (1/4) * u0
12 u0 , u1 = u1 , u2
13 return u2
14
15 try :
16 n = int ( input ( " Enter a non - negative integer n : " ) )
17 result = c om pu te _s eq ue nc e _ t e r m ( n )
18 print ( f " The { n } - th term of the sequence is : { result :.6 f } " )
19 except ValueError :
20 print ( " Invalid input . Please enter an integer . " )
21
19
Algorithms II Problem Set I
Exercise 10:
The Syracuse sequence is defined according to a parity condition as follows:
(
1
un if un is even
u0 ∈ N, un+1 = 2
3un + 1 if un is odd
The "Czech conjecture" states that for all initial values u0 ∈ N∗ , there exists a rank n for
which un = 1. For example, if u0 = 6 then u8 = 1.
n 0 1 2 3 4 5 6 7 8 9 10
un 6 3 10 5 16 8 4 2 1 4 2
Write an algorithm that asks the user to input the initial value u0 and determines and
displays the smallest value of n for which un = 1. Translate this algorithm into Python.
20
Algorithms II Problem Set I
Correction
Algorithm
Require: A positive integer u0
Ensure: The smallest integer n such that un = 1
Read u0
Initialize n = 0
Set current = u0
while current ̸= 1 do
if current mod 2 = 0 then
current = current/2
else
current = 3 × current + 1
end if
n=n+1
end while
Output n
Python Implementation
1 def collatz_steps () :
2 try :
3 u0 = int ( input ( " Enter a positive integer ( u0 ) : " ) )
4 if u0 <= 0:
5 print ( " Error : u0 must be a positive integer . " )
6 return
7 except ValueError :
8 print ( " Invalid input . Please enter an integer . " )
9 return
10
11 n = 0
12 current = u0
13 while current != 1:
14 if current % 2 == 0:
15 current = current // 2
16 else :
17 current = 3 * current + 1
18 n += 1
19 print ( f " The smallest n for which u_n = 1 is : { n } " )
20
21 collatz_steps ()
22
21
Algorithms II Problem Set I
Exercise 11:
To approximate the hypothetical limit of the sequence:
(
U0 = a
1+Un
Un+1 = 1+2U n
Find an algorithm that calculates the value of the sequence Un such that |Un − Un−1 | < ε
where ε = 10−6 , (where a is a strictly positive real number entered from the keyboard).
Translate this algorithm into Python.
22
Algorithms II Problem Set I
Correction
Algorithm
Require: A strictly positive real number a, tolerance ϵ = 10−6
Ensure: The smallest n such that |Un − Un−1 | < ϵ
Read a
if a ≤ 0 then
Output "Error: a must be a positive real number."
return
end if
Initialize Uprev = a, n = 0
repeat
Uprev
Compute Ucurr = 1 + 1+2·U prev
n=n+1
Compute diff = |Ucurr − Uprev |
Update Uprev = Ucurr
until diff < 10−6
Output Ucurr and n
Python Implementation
1 def c o m pu te _ s eq ue nc e_ te rm () :
2 try :
3 a = float ( input ( " Enter a strictly positive real number ( a ) :
"))
4 if a <= 0:
5 print ( " Error : a must be a positive real number . " )
6 return
7 except ValueError :
8 print ( " Invalid input . Please enter a valid real number . " )
9 return
10
11 epsilon = 1e -6
12 U_prev = a
13 n = 0
14
15 while True :
16 U_curr = 1 + U_prev / (1 + 2 * U_prev )
17 diff = abs ( U_curr - U_prev )
18 U_prev = U_curr
19 n += 1
20 if diff < epsilon :
21 break
22
23 print ( f " Converged to U_n = { U_curr :.10 f } after { n } iterations . "
)
24
25 c o m p u t e _s eq ue n c e_ te r m ()
26
23
Algorithms II Problem Set I
Exercise 12:
Consider the following sequence (Xn )n ∈ N:
(
X0 = A
1 A
Xn+1 = 2
Xn + Xn
where A is a strictly positive real number. Write an algorithm that asks the user to
input the value of A and then calculates and displays the value of the sequence (Xn ) (The
stopping point for iterations is |Xn −Xn−1 | < 10−9 ). Implement this algorithm in Python.
What does this algorithm calculate?
24
Algorithms II Problem Set I
Correction
Algorithm
Require: A strictly positive√real number A
Ensure: Approximation of A such that |Xn − Xn−1 | < 10−9
Read A
if A ≤ 0 then
Output "Error: A must be strictly positive."
return
end if
Initialize Xprev = A
repeat
Compute Xcurr = 0.5 × Xprev + Xprev
A
Python Implementation
25 n ew t o n_ r ap hson _sqr t ()
26
Exercise 13:
Let T be an array of integers of size N . Write an algorithm and the corresponding Python
program that:
26
Algorithms II Problem Set I
Correction
Algorithm
Require: Size N of array T and N integers as input
Ensure: Display array elements and their sum
Read N
if N ≤ 0 then
Output "Error: Array size must be positive."
return
end if
Initialize empty array T
for i = 0 to N − 1 do
Read integer x
Append x to T
end for
Output "Array: T "
Initialize total = 0
for x in T do
total = total + x
end for
Output "Sum: total"
Python Implementation
1 def array_operations () :
2 try :
3 N = int ( input ( " Enter the size of the array ( positive
integer ) : " ) )
4 if N <= 0:
5 print ( " Error : Array size must be positive . " )
6 return
7 except ValueError :
8 print ( " Invalid input . Please enter an integer . " )
9 return
10
11 T = []
12 print ( f " Enter { N } integers : " )
13 for i in range ( N ) :
14 while True :
15 try :
16 x = int ( input ( f " Element { i + 1}: " ) )
17 T . append ( x )
18 break
19 except ValueError :
20 print ( " Invalid input . Please enter an integer . " )
21
22 print ( " Array : " , T )
23 total = sum ( T )
24 print ( " Sum of elements : " , total )
25
26 array_operations ()
27
27
Algorithms II Problem Set I
Exercise 14:
Let T be an array of integers of size N . Write an algorithm and the corresponding Python
program that:
• Transfers the positive elements of T to the array T P OS and the strictly negative
elements to the array T N EG.
28
Algorithms II Problem Set I
Correction
Algorithm
Require: Size N of array T and N integers as input
Ensure: Display T , TPOS , and TNEG
Read N
if N ≤ 0 then
Output "Error: Array size must be positive."
return
end if
Initialize empty array T
for i = 0 to N − 1 do
Read integer x
Append x to T
end for
Output "Array: T "
Initialize empty arrays TPOS and TNEG
for x in T do
if x > 0 then
Append x to TPOS
else if x < 0 then
Append x to TNEG
end if
end for
Output "Positive elements: TPOS "
Output "Negative elements: TNEG "
Python Implementation
29
Algorithms II Problem Set I
Correction
1 def array_separation () :
2 try :
3 N = int ( input ( " Enter the size of the array ( positive
integer ) : " ) )
4 if N <= 0:
5 print ( " Error : Array size must be positive . " )
6 return
7 except ValueError :
8 print ( " Invalid input . Please enter an integer . " )
9 return
10
11 T = []
12 print ( f " Enter { N } integers : " )
13 for i in range ( N ) :
14 while True :
15 try :
16 x = int ( input ( f " Element { i + 1}: " ) )
17 T . append ( x )
18 break
19 except ValueError :
20 print ( " Invalid input . Please enter an integer . " )
21
22 T_POS = []
23 T_NEG = []
24 for x in T :
25 if x > 0:
26 T_POS . append ( x )
27 elif x < 0:
28 T_NEG . append ( x )
29
30 print ( " Original array : " , T )
31 print ( " Positive elements : " , T_POS )
32 print ( " Negative elements : " , T_NEG )
33
34 array_separation ()
35
30
Algorithms II Problem Set I
Exercise 15:
Let T be an array of real numbers of size N . Write an algorithm and the corresponding
Python program that:
• Calculates and displays the norm of the vector T given by the following formula:
P 1
2 2
norm = N
i=1 T [i]
31
Algorithms II Problem Set I
Correction
Algorithm
Require: Size N of array T and N real numbers as input
Ensure: Norm of the vector T
Read N
if N ≤ 0 then
Output "Error: Array size must be positive."
return
end if
Initialize empty array T
for i = 0 to N − 1 do
Read real number x
Append x to T
end for
Initialize sum_squares = 0
for x in T do
sum_squares = sum_squares + x2
end for
√
Compute norm = sum_squares
Output norm
Python Implementation
1 import math
2
3 def vector_norm () :
4 try :
5 N = int ( input ( " Enter the size of the array ( positive
integer ) : " ) )
6 if N <= 0:
7 print ( " Error : Array size must be positive . " )
8 return
9 except ValueError :
10 print ( " Invalid input . Please enter an integer . " )
11 return
12
13 T = []
14 print ( f " Enter { N } real numbers : " )
15 for i in range ( N ) :
16 while True :
17 try :
18 x = float ( input ( f " Element { i + 1}: " ) )
19 T . append ( x )
20 break
21 except ValueError :
22 print ( " Invalid input . Please enter a valid real
number . " )
23
24 sum_squares = sum ( x **2 for x in T )
25 norm = math . sqrt ( sum_squares )
26 print ( f " The norm of the vector is : { norm :.6 f } " )
27
28 vector_norm ()
29
32
Listing 18: Vector Norm Calculation
Algorithms II Problem Set I
Exercise 16:
Let v1 and v2 be two arrays of real numbers of the same size N . Write an algorithm and
the corresponding Python program that:
• Calculates and displays the distance d between the two vectors given by:
N
1 X
d= 2 (v1 [i] − v2 [i])2
N i=1
• Calculates and displays the dot product of the two vectors v1 and v2.
33
Algorithms II Problem Set I
Correction
Algorithm
Require: Size N of vectors v1 and v2 , and N real numbers for each vector
Ensure: Distance d and dot product p between the vectors
Read N
if N ≤ 0 then
Output "Error: Vector size must be positive."
return
end if
Initialize empty arrays v1 and v2
for i = 0 to N − 1 do
Read real number x for v1 [i]
Append x to v1
end for
for i = 0 to N − 1 do
Read real number y for v2 [i]
Append y to v2
end for
Initialize sum_diff = 0 and sum_dot = 0
for i = 0 to N − 1 do
diff = v1 [i] − v2 [i]
sum_diff = sum_diff + diff × diff
sum_dot = sum_dot + v1 [i] × v2 [i]
end for
Compute d = sum_diffN2
Compute p = sum_dot
Output d and p
Python Implementation
34
Algorithms II Problem Set I
Correction
11 v1 = []
12 v2 = []
13 print ( f " Enter { N } real numbers for vector v1 : " )
14 for i in range ( N ) :
15 while True :
16 try :
17 x = float ( input ( f " Element { i + 1}: " ) )
18 v1 . append ( x )
19 break
20 except ValueError :
21 print ( " Invalid input . Please enter a valid real
number . " )
22
23 print ( f " Enter { N } real numbers for vector v2 : " )
24 for i in range ( N ) :
25 while True :
26 try :
27 y = float ( input ( f " Element { i + 1}: " ) )
28 v2 . append ( y )
29 break
30 except ValueError :
31 print ( " Invalid input . Please enter a valid real
number . " )
32
33 sum_diff = 0.0
34 sum_dot = 0.0
35 for i in range ( N ) :
36 diff = v1 [ i ] - v2 [ i ]
37 sum_diff += diff * diff
38 sum_dot += v1 [ i ] * v2 [ i ]
39
40 distance = sum_diff / ( N * N )
41 dot_product = sum_dot
42
43 print ( f " Distance between vectors : { distance :.6 f } " )
44 print ( f " Dot product of vectors : { dot_product :.6 f } " )
45
46 vect or_operations ()
47
35
Algorithms II Problem Set I
Exercise 17:
Let T be an array of integers of size N . Write an algorithm and the corresponding Python
program that:
• Rearranges the elements of array T in reverse order without using a helper array.
36
Algorithms II Problem Set I
Correction
Algorithm
Require: Size N of array T and N integers as input
Ensure: Array T reversed in-place
Read N
if N ≤ 0 then
Output "Error: Array size must be positive."
return
end if
Initialize empty array T
for i = 0 to N − 1 do
Read integer x
Append x to T
end for
Output "Original array: T "
Initialize i = 0, j = N − 1
while i < j do
Swap T [i] and T [j]
i=i+1
j =j−1
end while
Output "Reversed array: T "
Python Implementation
37
Algorithms II Problem Set I
Correction
1 def r e v er s e _ a rr ay _ i n _ pl ac e () :
2 try :
3 N = int ( input ( " Enter the size of the array ( positive
integer ) : " ) )
4 if N <= 0:
5 print ( " Error : Array size must be positive . " )
6 return
7 except ValueError :
8 print ( " Invalid input . Please enter an integer . " )
9 return
10
11 T = []
12 print ( f " Enter { N } integers : " )
13 for i in range ( N ) :
14 while True :
15 try :
16 x = int ( input ( f " Element { i + 1}: " ) )
17 T . append ( x )
18 break
19 except ValueError :
20 print ( " Invalid input . Please enter an integer . " )
21
22 print ( " Original array : " , T )
23
24 # In - place reversal
25 i = 0
26 j = N - 1
27 while i < j :
28 T[i], T[j] = T[j], T[i]
29 i += 1
30 j -= 1
31
32 print ( " Reversed array : " , T )
33
34 r e v e r s e _a rr a y _i n_ pl a c e ()
35
38
Algorithms II Problem Set I
Exercise 18:
Let T be an array of real numbers of size N . Write an algorithm and the corresponding
Python program that:
• Determines the maximum, minimum, the index of the maximum, and the index of
the minimum of T (If the array T contains multiple maximums and minimums, the
program will display the position of the first occurrence encountered).
39
Algorithms II Problem Set I
Correction
Algorithm
Require: Size N of array T and N real numbers as input
Ensure: Maximum value, minimum value, and their indices (first occurrence)
Read N
if N ≤ 0 then
Output "Error: Array size must be positive."
return
end if
Initialize empty array T
for i = 0 to N − 1 do
Read real number x
Append x to T
end for
Output "Array: T "
Initialize max_val = T [0], min_val = T [0]
Initialize max_index = 0, min_index = 0
for i = 1 to N − 1 do
if T [i] > max_val then
max_val = T [i]
max_index = i
end if
if T [i] < min_val then
min_val = T [i]
min_index = i
end if
end for
Output "Maximum: max_val at index max_index"
Output "Minimum: min_val at index min_index"
Python Implementation
40
Algorithms II Problem Set I
Correction
1 def f i n d_ ma x_ min_ in di ce s () :
2 try :
3 N = int ( input ( " Enter the size of the array ( positive
integer ) : " ) )
4 if N <= 0:
5 print ( " Error : Array size must be positive . " )
6 return
7 except ValueError :
8 print ( " Invalid input . Please enter an integer . " )
9 return
10
11 T = []
12 print ( f " Enter { N } real numbers : " )
13 for i in range ( N ) :
14 while True :
15 try :
16 x = float ( input ( f " Element { i + 1}: " ) )
17 T . append ( x )
18 break
19 except ValueError :
20 print ( " Invalid input . Please enter a valid real
number . " )
21
40 f i n d _ m a x_ min_ in di ce s ()
41
41
Algorithms II Problem Set I
Exercise 19:
Write an algorithm and the corresponding Python program to calculate the value of a
polynomial of degree N .
42
Algorithms II Problem Set I
Correction
Algorithm
Require: Degree N of the polynomial, N + 1 coefficients a0 , a1 , ..., aN , and a real
number x
Ensure: Value of the polynomial P (x) = a0 xN + a1 xN −1 + · · · + aN
Read N
if N < 0 then
Output "Error: Degree must be non-negative."
return
end if
Initialize array A of size N + 1
for i = 0 to N do
Read coefficient ai
Append ai to A
end for
Read real number x
Initialize result = A[0]
for i = 1 to N do
result = result × x + A[i]
end for
Output result
Python Implementation
43
Algorithms II Problem Set I
Correction
11 coefficients = []
12 print ( f " Enter { N + 1} coefficients from highest degree to
lowest : " )
13 for i in range ( N + 1) :
14 while True :
15 try :
16 coeff = float ( input ( f " Coefficient for x ^{ N - i }: " )
)
17 coefficients . append ( coeff )
18 break
19 except ValueError :
20 print ( " Invalid input . Please enter a valid real
number . " )
21
22 try :
23 x = float ( input ( " Enter the value of x : " ) )
24 except ValueError :
25 print ( " Invalid input for x . Please enter a real number . " )
26 return
27
28 result = coefficients [0]
29 for i in range (1 , N + 1) :
30 result = result * x + coefficients [ i ]
31
44
Algorithms II Problem Set I
Exercise 20:
Let M be a matrix of integers of size L × C. Write an algorithm and the corresponding
Python program that:
45
Algorithms II Problem Set I
Correction
Algorithm
Require: Number of rows L and columns C of matrix M , followed by L × C
integers
Ensure: Display matrix, total sum, row sums, and column sums
Read L
Read C
if L ≤ 0 OR C ≤ 0 then
Output "Error: Matrix dimensions must be positive."
return
end if
Initialize empty matrix M
for i = 0 to L − 1 do
Create empty row R
for j = 0 to C − 1 do
Read integer x
Append x to R
end for
Append R to M
end for
Output "Matrix:"
for i = 0 to L − 1 do
Output M [i]
end for
Initialize total = 0
for i = 0 to L − 1 do
for j = 0 to C − 1 do
total = total + M [i][j]
end for
end for
Output "Total sum: total"
Output "Row sums:"
for i = 0 to L − P1 do
row_sum = M [i]
Output "Row i + 1: row_sum"
end for
Output "Column sums:"
for j = 0 to C − 1 do
col_sum = 0
for i = 0 to L − 1 do
col_sum = col_sum + M [i][j]
end for
Output "Column j + 1: col_sum"
end for
Python Implementation
46
Algorithms II Problem Set I
Correction
47
Algorithms II Problem Set I
Exercise 21:
Let A be a square matrix of integers of order N . Write an algorithm and the corresponding
Python program that:
48
Algorithms II Problem Set I
Correction
Algorithm
Require: Order N of square matrix A, followed by N × N integers
Ensure: Non-zero count, trace, diagonal product, transpose, and A2
Read N
if N ≤ 0 then
Output "Error: Matrix order must be positive."
return
end if
Initialize N × N matrix A
for i = 0 to N − 1 do
for j = 0 to N − 1 do
Read A[i][j]
end for
end for
Initialize nonzero_count = 0
Initialize trace = 0
Initialize diag_product = 1
for i = 0 to N − 1 do
for j = 0 to N − 1 do
if A[i][j] ̸= 0 then
nonzero_count = nonzero_count + 1
end if
end for
trace = trace + A[i][i]
diag_product = diag_product × A[i][i]
end for
Create transpose matrix AT of size N × N
for i = 0 to N − 1 do
for j = 0 to N − 1 do
AT [i][j] = A[j][i]
end for
end for
Create matrix A2 of size N × N
for i = 0 to N − 1 do
for j = 0 to N − 1 do
sum = 0
for k = 0 to N − 1 do
sum = sum + A[i][k] × A[k][j]
end for
A2 [i][j] = sum
end for
end for
Output nonzero_count, trace, diag_product, AT , and A2
Python Implementation
49
Algorithms II Problem Set I
Correction
11 # Read matrix A
12 A = []
13 print ( f " Enter { N } rows with { N } integers each : " )
14 for i in range ( N ) :
15 row = []
16 while len ( row ) < N :
17 try :
18 x = int ( input ( f " Row { i + 1} , Column { len ( row ) + 1}:
"))
19 row . append ( x )
20 except ValueError :
21 print ( " Invalid input . Please enter an integer . " )
22 A . append ( row )
23
24 # Count non - zero elements
25 nonzero_count = sum (1 for row in A for val in row if val != 0)
26
27 # Compute trace and diagonal product
28 trace = 0
29 diag_product = 1
30 for i in range ( N ) :
31 trace += A [ i ][ i ]
32 diag_product *= A [ i ][ i ]
33
34 # Compute transpose
35 A_T = [[ A [ j ][ i ] for j in range ( N ) ] for i in range ( N ) ]
36
37 # Compute A ^2
38 A2 = [[0 for _ in range ( N ) ] for _ in range ( N ) ]
39 for i in range ( N ) :
40 for j in range ( N ) :
41 for k in range ( N ) :
42 A2 [ i ][ j ] += A [ i ][ k ] * A [ k ][ j ]
43
44 # Output results
45 print ( " \ nOriginal Matrix A : " )
46 for row in A :
47 print ( row )
48
49 print ( f " Number of non - zero elements : { nonzero_count } " )
50 print ( f " Trace of A : { trace } " )
51 print ( f " Product of diagonal elements : { diag_product } " )
52
50
Algorithms II Problem Set I
Correction
51
Algorithms II Problem Set I
Exercise 22:
Let M be a matrix of integers of size L × C. Write an algorithm and the corresponding
Python program that:
52
Algorithms II Problem Set I
Correction
Algorithm
Require: Number of rows L and columns C of matrix M , followed by L × C
integers
Ensure: Display matrix M , vector V (flattened row-wise), and total sum
Read L
Read C
if L ≤ 0 OR C ≤ 0 then
Output "Error: Matrix dimensions must be positive."
return
end if
Initialize empty matrix M
for i = 0 to L − 1 do
Create empty row R
for j = 0 to C − 1 do
Read integer x
Append x to R
end for
Append R to M
end for
Initialize empty vector V
for i = 0 to L − 1 do
for j = 0 to C − 1 do
Append M [i][j] to V
end for
end for
Output "Matrix:"
for i = 0 to L − 1 do
Output M [i]
end for
Output "Vector V (row-wise):"
Output V
Python Implementation
53
Algorithms II Problem Set I
Correction
1 def matrix_to_vector () :
2 try :
3 L = int ( input ( " Enter number of rows ( positive integer ) : " ) )
4 C = int ( input ( " Enter number of columns ( positive integer ) :
"))
5 if L <= 0 or C <= 0:
6 print ( " Error : Matrix dimensions must be positive . " )
7 return
8 except ValueError :
9 print ( " Invalid input . Please enter integers for dimensions .
")
10 return
11
12 M = []
13 print ( f " Enter { L } rows with { C } integers each : " )
14 for i in range ( L ) :
15 row = []
16 while len ( row ) < C :
17 try :
18 x = int ( input ( f " Row { i + 1} , Column { len ( row ) + 1}:
"))
19 row . append ( x )
20 except ValueError :
21 print ( " Invalid input . Please enter an integer . " )
22 M . append ( row )
23
24 V = []
25 for row in M :
26 V . extend ( row )
27
28 print ( " \ nMatrix : " )
29 for row in M :
30 print ( row )
31 print ( " \ nVector ( row - wise ) : " )
32 print ( V )
33
34 matrix_to_vector ()
35
54
Algorithms II Problem Set I
Exercise 23:
Write an algorithm and the corresponding Python program that enables:
55
Algorithms II Problem Set I
Correction
Algorithm
Require: Two matrices A and B, scalar k, and operation type
Ensure: Result of selected matrix operation
Read operation type: "add", "scalar", or "multiply"
if operation is "add" then
Read dimensions L × C for matrices A and B
Read matrix A of size L × C
Read matrix B of size L × C
Initialize matrix C of size L × C
for i = 0 to L − 1 do
for j = 0 to C − 1 do
C[i][j] = A[i][j] + B[i][j]
end for
end for
Output matrix C
else if operation is "scalar" then
Read scalar k
Read dimensions L × C for matrix A
Read matrix A of size L × C
Initialize matrix B of size L × C
for i = 0 to L − 1 do
for j = 0 to C − 1 do
B[i][j] = k × A[i][j]
end for
end for
Output matrix B
else if operation is "multiply" then
Read dimensions L1 × C1 for matrix A
Read dimensions L2 × C2 for matrix B
if C1 ̸= L2 then
Output "Error: Matrices cannot be multiplied."
return
end if
Read matrix A of size L1 × C1
Read matrix B of size L2 × C2
Initialize matrix C of size L1 × C2
for i = 0 to L1 − 1 do
for j = 0 to C2 − 1 do
C[i][j] = 0
for k = 0 to C1 − 1 do
C[i][j] = C[i][j] + A[i][k] × B[k][j]
end for
end for
end for
Output matrix C
end if
56
Algorithms II Problem Set I
Correction
Python Implementation
57
Algorithms II Problem Set I
Correction
6 elif choice == ’2 ’:
7 try :
8 k = float ( input ( " Enter scalar value : " ) )
9 L = int ( input ( " Enter number of rows : " ) )
10 C = int ( input ( " Enter number of columns : " ) )
11 print ( " Matrix A : " )
12 A = read_matrix (L , C )
13 result = ma tr ix_ sc al ar_ mu lt (k , A )
14 print ( f " Result ( A * { k }) : " )
15 for row in result :
16 print ( row )
17 except ValueError as e :
18 print ( f " Error : { e } " )
19
20 elif choice == ’3 ’:
21 try :
22 print ( " Matrix A dimensions : " )
23 L1 = int ( input ( " Rows : " ) )
24 C1 = int ( input ( " Columns : " ) )
25 print ( " Matrix B dimensions : " )
26 L2 = int ( input ( " Rows : " ) )
27 C2 = int ( input ( " Columns : " ) )
28 if C1 != L2 :
29 print ( " Error : Matrices cannot be multiplied . " )
30 return
31 print ( " Matrix A : " )
32 A = read_matrix ( L1 , C1 )
33 print ( " Matrix B : " )
34 B = read_matrix ( L2 , C2 )
35 result = matrix_multiply (A , B )
36 print ( " Result ( A * B ) : " )
37 for row in result :
38 print ( row )
39 except ValueError as e :
40 print ( f " Error : { e } " )
41
42 else :
43 print ( " Invalid choice . " )
44
45 main ()
46
58