0% found this document useful (0 votes)
73 views20 pages

Ucest105 Algorithmic Thinking With Python, May 2025 Solved

UCEST 105 Algorithmic Thinking WITH Python, MAY 2025 Solved Previous Year Question Paper

Uploaded by

gfdg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views20 pages

Ucest105 Algorithmic Thinking With Python, May 2025 Solved

UCEST 105 Algorithmic Thinking WITH Python, MAY 2025 Solved Previous Year Question Paper

Uploaded by

gfdg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

03UCEST 105122401

Res NO. : Name:


APJ ABDUL KALAM TECHNOLOGICAL UNIVERSITY
B.Tech Degree S 1 (S) Examination May 2025 (2024 Scheme)

Course Code: UCEST105

Course Name: ALGORITHNIC THINKING WITH PYTHON

Max. Marks: 60 Duration: 2 hours 30 minutes

PART A

(Answer all questions. Each question carries 3 marks) CO Marks

Identify the most suitable problem-solving strategies for the following use Col (3)

cases. Justify your answer:

i) You are solving a complex Sudoku puzzle and are unsure how to

proceed as you approach the final few cells.

ii) You are tasked with planning a family trip that involves selecting a

estimation, booking flights, and finding accommodation within a

What will be the result of the following expressions in Python? Col, (3)

i) (50 - 5 * 6) // 4 •C04

ii) not (10 < 5) or (5 = = 5)

iii) True and 5

at are the advantages of using pseudocode overdirectly writing the code? - C02 (3)

Draw a flowchart to print integers below 50. C02 (3)

Given the following list: C03, (3)

mbers - [10, 20, 30, 40, 50, 60, 70, 80, 90] C04
Write the slicing expressions to:

I. Extract the first 5 elements.

2. Extract every second element starting from the first element.

Page 1 of 4
03UCEST 10512240 i

3. Reverse the list using slicing.

What is circularity in recursion? How can you prevent circularity in recursive C03 (3)

functions?

Compare Dynamic programming and Recursioli in terms of their approach, C04 (3)

efficiency, and use cases.

What is the brute-force computational problem-solving approach, and how C04 (3)

many maximum attempts are required to guarantee opening a four-digit

numerical padlock (digits ranging from 0 to 9) using this approach?

PART 8

(Answer any one full question from each module, each question carries 9 marks)

Module -1

9 a) Walkthrough the six problem-solving steps to calculate the area ofa circle. Col (6)

b) Whatarethe basic datatypes in python?Provide examples foreach. Col, (3)

C04
10 a) What isthe difference between algorithms and heuristics in problem-solving? Col (5)

Provide an example where heuristics lead to a faster solution than an

algorithm.

b) Write apython prograin to convertthetilne input inminutesto hours Col, (4)

and minutes. For example, 85 minutes is 1 hour 25 minutes. C04

11 a) Youvisitashoptobuyanewmobile. Inconnectionwiththefestiveseason, C02 (5)

the shop offers a 10% discount on all mobiles. In addition, the shop also gives

a flat exchange price of 1000 for old mobiles. Draw a flowchart to input the

original price of the mobile and print its selling price. Note that all customers

may not have an old mobile for exchange.

Page 2 of 4
03UCEST 105122401

b) If the three sides ofa triangle are input, write an algorithm/pseudocode to C02 (4)

check whether the triangle is isosceles, equilateral, or scalene.

12 a) Writepseudocodetodeterminetheaverageageofstudents inaclass.The C02 (5)

user will stop giving the input by giving the age as 0.

b) Drawa flowchartto findthe largestnumberfrom aseries ofnumbersentered C02 (4)

sequentially.

Module -3

13 a) What arethe primary differences between lists, tuples, and strings in python C03, (3)

in terms of mutability, usage. and methods? C04

b) Write a Python function isvalid_mobile_no to check whether a given C03 (3)

number is a valid mobile number or not. The program should validate the

number based on the following rules:

I. The number must contain exactly 10 digits.

2. The first digit of the number must be 7, 8, or 9.

c) Writearecursive function in pythonto find theGCDoftwonumbers. C03 (3)

14 a) Write a python program to Input two lists from the user. Merge these lists C03, (4)

into a third list such that in the merged list, all even numbers occur first C04

followed by odd numbers. Both the even numbers and odd numbers should be

in sorted order.

b) Write a recursive function to multiply two positive numbers. Trace the C03 (5)

function calls for multiplying 3 and 4, and explain the changes in the call

stack during execution.

Module -4

15 a) Illustratetheprocessofsortingthearray[15,8,3,12,6,10,4, l]usingthe C04 (6)

merge sort algorithm. Draw a diagram showing how the array is split and

merged at each stage.

Page 3 of 4
03UCEST 10512240 l

b) What is memoization, and how does it differ from tabulation in dynamic C04 (3)
- programming?

16 a) A vending machine needs to return change to a customer using the least C04 (5)

number of coins. The machine has an infinite supply of coins of

denominations. Implement the greedy algorithm to determine the

combination of coins that minimizes the total number of coins used to make a

given amount of change.

b) Compare Greedy Algorithms and Dynamic programming in terms of their C04 (4)

approach, solution guarantee, and applicable scenarios. Provide examples

where each approach is preferred.


***

Page 4 of 4
UCEST105 ALGORITHMIC THINKING WITH PYTHON - SOLVED PYQ

B.Tech Degree S1 (S) Examination May 2025 (2024 Scheme)


PART A
(Answer all questions. Each question carries 3 marks)

1. Identify the most suitable problem-solving strategies for the following use cases. Justify your
answer:

i) You are solving a complex Sudoku puzzle and are unsure how to proceed as you approach the
final few cells. (3 Marks)

Strategy: Backtracking.

Justification: Sudoku is a classic constraint satisfaction problem. When nearing the final cells, if a
number is placed and later found to violate a rule (i.e., a dead end is reached), the solver must undo
the last move and systematically try an alternative number. Backtracking is the strategy that
involves building a solution step-by-step and abandoning (backtracking) any partial path that is
found not to satisfy all constraints.

ii) You are tasked with planning a family trip that involves selecting a destination, booking flights,
and finding accommodation within a budget. (3 Marks)

Strategy: Means-Ends Analysis (MEA).

Justification: MEA is suitable because the overall goal (a successful trip within budget) requires
identifying and reducing the differences between the current state (no plan) and the desired final
state. The planning is divided into sub-problems (ends), such as "find accommodation," "book
flights," and "select destination." MEA systematically addresses these sub-goals, ensuring constraints
like the budget are maintained throughout the process.

2. What will be the result of the following expressions in Python? (3 Marks)

i) (50 - 5 * 6) // 4

Result: 5

• Step 1 (Multiplication): 5 * 6 = 30

• Step 2 (Subtraction): 50 - 30 = 20

• Step 3 (Integer Division //): 20 // 4 = 5

ii) not (10 < 5) or (5 == 5)

Result: True

• Step 1 (Comparisons): (10 < 5) is False. (5 == 5) is True.

• Step 2 (Not): not False is True.

BINSHAN V K – SREE CHITRA THIRUNAL COLLEGE OF ENGINEERING TRIVANDRUM 1


UCEST105 ALGORITHMIC THINKING WITH PYTHON - SOLVED PYQ

• Step 3 (Or): True or True is True.

iii) True and 5

Result: 5

• In Python, non-zero numerical values are considered logically True. In a boolean AND
operation, if the first operand is true (True), the result is the second operand.

3. What are the advantages of using pseudocode over directly writing the code? (3 Marks)

Pseudocode offers several advantages for algorithm development:

1. Clarity and Readability: It uses natural language and mathematical notation, making the
logic easy to follow for both technical and non-technical individuals, irrespective of the
target programming language.

2. Focus on Logic: It allows the developer to concentrate purely on the structural logic of the
algorithm without being constrained by the strict syntax rules of a specific programming
language.

3. Language Independence: Since it is not tied to a specific compiler or interpreter,


pseudocode provides a universal way to document the structure of a solution, which can
then be implemented easily in any language.

4. Draw a flowchart to print integers below 50. (3 Marks)

(Self-Correction: Since I cannot draw a diagram, I will describe the required flowchart structure and
steps.)

Flowchart Description:

1. Start: (Terminal Symbol)

2. Initialization: Set a variable i = 1 (Process Symbol).

3. Decision Loop: Check the condition Is i < 50? (Decision Symbol).

o If Yes, follow the flowline to the output step.

o If No, follow the flowline to End.

4. Output: Print the value of i (Input/Output Symbol).

5. Increment: Set i = i + 1 (Process Symbol).

6. Loop Back: Draw a flowline returning to the Decision Loop (Step 3).

7. End: (Terminal Symbol).

BINSHAN V K – SREE CHITRA THIRUNAL COLLEGE OF ENGINEERING TRIVANDRUM 2


UCEST105 ALGORITHMIC THINKING WITH PYTHON - SOLVED PYQ

5. Given the following list: numbers =

Write the slicing expressions to: (3 Marks)

1. Extract the first 5 elements.

numbers[:5]

2. Extract every second element starting from the first element.

numbers[::2] (This would result in:)

3. Reverse the list using slicing.

numbers[::-1]

6. What is circularity in recursion? How can you prevent circularity in recursive functions? (3
Marks)

Circularity in Recursion: Circularity, also known as infinite recursion, occurs when a recursive
function calls itself indefinitely. This happens because the function fails to reach a base case, or the
input modifications in the recursive step do not drive the function toward the base case. This
ultimately causes the program to crash due to a stack overflow error.

Prevention: Circularity is prevented by ensuring two conditions are always met:

1. Defining a Base Case: A clear condition must be defined that stops the recursion and returns
a value without making further recursive calls.

2. Guaranteeing Convergence: Each recursive call must operate on a modified input that is
strictly "closer" to satisfying the base case condition than the previous input.

7. Compare Dynamic Programming and Recursion in terms of their approach, efficiency, and use
cases. (3 Marks)

Feature Dynamic Programming (DP) Recursion (General)

Solves problems by breaking them into Solves problems by breaking them


overlapping subproblems and stores results to into smaller subproblems. If
Approach
reuse them, typically working bottom-up subproblems overlap, it solves them
(Tabulation) or top-down with memoization. repeatedly.

Can be highly inefficient (exponential


Highly efficient for problems with overlapping
time complexity) for problems with
Efficiency subproblems because redundant calculations are
overlapping subproblems, due to
eliminated through storing results.
recalculation.

BINSHAN V K – SREE CHITRA THIRUNAL COLLEGE OF ENGINEERING TRIVANDRUM 3


UCEST105 ALGORITHMIC THINKING WITH PYTHON - SOLVED PYQ

Optimization problems (e.g., shortest path, Simple solutions, tree traversals, or


Use
knapsack), sequences where results must be problems without high overlap in
Cases
reused. subproblems.

8. What is the brute-force computational problem-solving approach, and how many maximum
attempts are required to guarantee opening a four-digit numerical padlock (digits ranging from 0
to 9) using this approach? (3 Marks)

Brute-Force Approach: Brute-force is a straightforward, general-purpose problem-solving technique


that involves systematically enumerating and checking all possible solutions or candidates until the
correct solution is found. While it guarantees finding the solution if one exists, it is often the least
efficient method computationally.

Maximum Attempts: A four-digit numerical padlock, using digits 0 through 9, has 10 possibilities for
each position.

• Total combinations = $10 \times 10 \times 10 \times 10 = 10^4$

• Maximum attempts required to guarantee opening the padlock is 10,000.

PART B

(Answer any one full question from each module, each question carries 9 marks)

Module - 1
9. a) Walk through the six problem-solving steps to calculate the area of a circle. (6 Marks)

The calculation of the area of a circle ($\text{Area} = \pi r^2$) follows these typical problem-solving
steps:

1. Understand the Problem (Definition): The goal is to determine the area of a circle. The
required input is the radius ($r$), and the necessary constant is $\pi$. The output must be
the calculated area.

2. Devise a Plan (Algorithm Design): Formulate the sequence of steps. Step 1: Get the radius
$r$. Step 2: Use the formula $A = \pi \times r \times r$. Step 3: Display the result $A$.

3. Carry out the Plan (Implementation): Implement the algorithm using code or pseudocode.
(e.g., In Python: import math; r = input(); area = math.pi * r**2; print(area)).

BINSHAN V K – SREE CHITRA THIRUNAL COLLEGE OF ENGINEERING TRIVANDRUM 4


UCEST105 ALGORITHMIC THINKING WITH PYTHON - SOLVED PYQ

4. Review/Look Back (Verification): Test the implementation with known values (e.g., if $r=1$,
the area should be $\pi$). Ensure the output matches expectations and handles different
inputs correctly.

5. Refinement: Improve the solution, perhaps by adding input validation (e.g., ensuring the
radius is a positive number).

6. Documentation: Clearly document the purpose, input requirements, formula used, and
expected output of the program.

9. b) What are the basic data types in Python? Provide examples for each. (3 Marks)

The basic data types in Python include:

1. Numeric Types: Used for mathematical operations.

o Example (Integer): age = 25

o Example (Float): price = 19.99

2. Boolean Type: Represents logical values (True or False).

o Example: is_active = True

3. Sequence Types: Ordered collections.

o Example (String): Immutable sequence of characters: word = "Python"

o Example (List): Mutable sequence: items = [1, 'a', 3.5]

o Example (Tuple): Immutable sequence: coordinates = (10, 20)

10. a) What is the difference between algorithms and heuristics in problem-solving? Provide an
example where heuristics lead to a faster solution than an algorithm. (5 Marks)

Algorithm: An algorithm is a precise, unambiguous set of rules or instructions designed to solve a


specific problem. It is guaranteed to find the correct, or optimal, solution in a finite number of
steps. Algorithms prioritize correctness and completeness over execution speed in non-polynomial
time problems. Heuristic: A heuristic is a technique, or "rule of thumb," that aims to quickly find a
good enough, though not necessarily optimal or guaranteed, solution. Heuristics are used when
the search space is too vast for an algorithm to explore exhaustively, prioritizing speed and
efficiency.

Example of Faster Heuristic Solution: Problem: A chess engine needs to determine the best move in
a complex game state.

• Algorithm (Brute-Force/Minimax Search): A complete algorithmic search would require


checking every possible move sequence for dozens of moves ahead, which is
computationally impossible within a reasonable time.

BINSHAN V K – SREE CHITRA THIRUNAL COLLEGE OF ENGINEERING TRIVANDRUM 5


UCEST105 ALGORITHMIC THINKING WITH PYTHON - SOLVED PYQ

• Heuristic (Evaluation Function): Chess engines use heuristic evaluation functions (e.g.,
assigning point values to pieces, controlling the center of the board) to quickly evaluate the
quality of a game state. By using this rule of thumb, the engine only searches promising
branches of the game tree, leading to a decision that is fast enough for real-time play, even
if it might not be the absolute mathematical best move.

10. b) Write a Python program to convert the time input in minutes to hours and minutes. For
example, 85 minutes is 1 hour 25 minutes. (4 Marks)

# Python program to convert total minutes to hours and minutes

def convert_minutes(total_minutes):

# Use integer division (//) to find the number of full hours

hours = total_minutes // 60

# Use the modulo operator (%) to find the remaining minutes

minutes = total_minutes % 60

# Output

print(f"{total_minutes} minutes is {hours} hour(s) and {minutes} minutes.")

# Taking input (assuming total_minutes = 85 for the example)

input_time = 85

convert_minutes(input_time)

# Example Output: 85 minutes is 1 hour(s) and 25 minutes.

Module - 2
11. a) Draw a flowchart to input the original price of the mobile and print its selling price,
considering a 10% discount and an optional flat exchange price of 1000 for old mobiles. (5 Marks)

(Self-Correction: Since I cannot draw a diagram, I will describe the required flowchart structure and
steps.)

Flowchart Description:

1. Start (Terminal Symbol)

BINSHAN V K – SREE CHITRA THIRUNAL COLLEGE OF ENGINEERING TRIVANDRUM 6


UCEST105 ALGORITHMIC THINKING WITH PYTHON - SOLVED PYQ

2. Input: Read OriginalPrice (Input/Output Symbol).

3. Process (Calculate Discount): DiscountedPrice = OriginalPrice * 0.90 (Process Symbol).

4. Input/Decision: Read Exchange (e.g., 'Y' or 'N' indicating if the customer has an old mobile).
(Input/Output Symbol).

5. Decision Check: Is Exchange == 'Y'? (Decision Symbol).

o If Yes (Exchange Applicable): Follow flowline to Step 6.

o If No (No Exchange): Follow flowline to Step 7.

6. Process (Apply Exchange): SellingPrice = DiscountedPrice - 1000 (Process Symbol). Go to


Step 8.

7. Process (No Change): SellingPrice = DiscountedPrice (Process Symbol).

8. Output: Print SellingPrice (Input/Output Symbol).

9. End (Terminal Symbol).

11. b) If the three sides of a triangle are input, write an algorithm/pseudocode to check whether
the triangle is isosceles, equilateral, or scalene. (4 Marks)

// ALGORITHM: CLASSIFY_TRIANGLE_TYPE

START

INPUT SideA, SideB, SideC

// Check if sides are valid (Triangle Inequality Check - Optional but robust)

// IF (SideA + SideB <= SideC) OR (SideA + SideC <= SideB) OR (SideB + SideC <= SideA) THEN

// OUTPUT "Not a Valid Triangle"

// RETURN

// 1. Equilateral Check (all sides equal)

IF SideA == SideB AND SideB == SideC THEN

OUTPUT "Equilateral Triangle"

// 2. Isosceles Check (exactly two sides equal)

ELSE IF SideA == SideB OR SideA == SideC OR SideB == SideC THEN

OUTPUT "Isosceles Triangle"

BINSHAN V K – SREE CHITRA THIRUNAL COLLEGE OF ENGINEERING TRIVANDRUM 7


UCEST105 ALGORITHMIC THINKING WITH PYTHON - SOLVED PYQ

// 3. Scalene Check (no sides equal)

ELSE

OUTPUT "Scalene Triangle"

END

12. a) Write pseudocode to determine the average age of students in a class. The user will stop
giving the input by giving the age as 0. (5 Marks)

// PSEUDOCODE: AVERAGE_AGE_CALCULATOR

START

SET TotalAge = 0

SET StudentCount = 0

// Start Input Loop

LOOP

INPUT Age

// Stop condition (Sentinel value)

IF Age == 0 THEN

BREAK LOOP

// Accumulate valid data

IF Age > 0 THEN

TotalAge = TotalAge + Age

StudentCount = StudentCount + 1

END LOOP

// Calculate and Output Result

IF StudentCount > 0 THEN

BINSHAN V K – SREE CHITRA THIRUNAL COLLEGE OF ENGINEERING TRIVANDRUM 8


UCEST105 ALGORITHMIC THINKING WITH PYTHON - SOLVED PYQ

SET AverageAge = TotalAge / StudentCount

OUTPUT "Total Students: ", StudentCount

OUTPUT "The Average Age is: ", AverageAge

ELSE

OUTPUT "No valid ages were entered."

END

12. b) Draw a flowchart to find the largest number from a series of numbers entered sequentially.
(4 Marks)

(Self-Correction: Since I cannot draw a diagram, I will describe the required flowchart structure and
steps.)

Flowchart Description (Assuming the user inputs N numbers, or uses a simple counter):

1. Start (Terminal Symbol)

2. Initialization: Initialize Largest = -Infinity or read the first input and set Largest to that value.
Initialize Count = 1 and read N (total numbers). (Process/Input Symbols).

3. Loop Preparation: Read CurrentNumber (Input/Output Symbol).

4. Comparison Decision: Is CurrentNumber > Largest? (Decision Symbol).

o If Yes: Largest = CurrentNumber (Process Symbol).

o If No: Proceed to next step.

5. Increment: Count = Count + 1 (Process Symbol).

6. Loop Control: Is Count <= N? (Decision Symbol).

o If Yes: Loop back to Step 3 (Read CurrentNumber).

o If No: Proceed to Output.

7. Output: Print Largest (Input/Output Symbol).

8. End (Terminal Symbol).

Module - 3
13. a) What are the primary differences between lists, tuples, and strings in Python in terms of
mutability, usage, and methods? (3 Marks)

BINSHAN V K – SREE CHITRA THIRUNAL COLLEGE OF ENGINEERING TRIVANDRUM 9


UCEST105 ALGORITHMIC THINKING WITH PYTHON - SOLVED PYQ

Feature List Tuple String

Mutable. Elements can


Immutable. Elements cannot be Immutable. Characters
Mutability be added, removed, or
changed after creation. cannot be changed.
changed.

Collections that require Fixed collections (e.g., configuration


Handling text and
Usage frequent modifications settings, database records) where
sequential character data.
or resizing. data integrity must be maintained.

Modification methods: Text processing methods:


Non-modification methods: count(),
Methods append(), insert(), upper(), split(), replace()
index().
remove(), sort(). (return new string).

13. b) Write a Python function is_valid_mobile_no to check whether a given number is a valid
mobile number or not, based on the rules: 1. Exactly 10 digits. 2. First digit is 7, 8, or 9. (3 Marks)

def is_valid_mobile_no(number_str):

"""Checks if a string represents a valid mobile number based on rules 1 and 2."""

# Rule 1: Must contain exactly 10 digits

if len(number_str) != 10:

return False

# (Optional: check if all characters are digits)

if not number_str.isdigit():

return False

# Rule 2: First digit must be 7, 8, or 9

first_digit = number_str

if first_digit not in ('7', '8', '9'):

return False

# If both rules pass

return True

BINSHAN V K – SREE CHITRA THIRUNAL COLLEGE OF ENGINEERING TRIVANDRUM 10


UCEST105 ALGORITHMIC THINKING WITH PYTHON - SOLVED PYQ

# Example Tests:

# print(is_valid_mobile_no("9876543210")) # True

# print(is_valid_mobile_no("6789012345")) # False (First digit must be 7, 8, or 9)

13. c) Write a recursive function in python to find the GCD of two numbers. (3 Marks)

The GCD (Greatest Common Divisor) is typically found using the Euclidean algorithm, which is
naturally recursive.

def recursive_gcd(a, b):

# Base Case: When b becomes 0, a is the GCD

if b == 0:

return a

# Recursive Step: GCD(a, b) is the same as GCD(b, a % b)

else:

return recursive_gcd(b, a % b)

# Example Usage

# print(recursive_gcd(48, 18)) # Output: 6

14. a) Write a Python program to Input two lists from the user. Merge these lists into a third list
such that in the merged list, all even numbers occur first followed by odd numbers. Both the even
numbers and odd numbers should be in sorted order. (4 Marks)

# Assuming L1 and L2 are inputted or defined

list1 =

list2 =

# 1. Merge the lists

merged_list = list1 + list2

even_list = []

odd_list = []

# 2. Separate into Even and Odd lists

BINSHAN V K – SREE CHITRA THIRUNAL COLLEGE OF ENGINEERING TRIVANDRUM 11


UCEST105 ALGORITHMIC THINKING WITH PYTHON - SOLVED PYQ

for num in merged_list:

if num % 2 == 0:

even_list.append(num)

else:

odd_list.append(num)

# 3. Sort both lists

even_list.sort() #

odd_list.sort() #

# 4. Combine: Evens first, then Odds

final_list = even_list + odd_list

print("Final sorted list (Evens then Odds):", final_list)

# Output:

14. b) Write a recursive function to multiply two positive numbers. Trace the function calls for
multiplying 3 and 4, and explain the changes in the call stack during execution. (5 Marks)

Recursive Multiplication Function:

def multiply_recursive(a, b):

# Base Case: Multiplication by 0 returns 0

if b == 0:

return 0

# Recursive Step: a * b = a + (a * (b - 1))

return a + multiply_recursive(a, b - 1)

Trace for multiplying 3 and 4 and Call Stack Explanation:

Call Action Stack State (Growth) Return Value

1 multiply_recursive(3, 4) [Call 1] $3 + R_2$

2 multiply_recursive(3, 3) [Call 1, Call 2] $3 + R_3$

3 multiply_recursive(3, 2) [Call 1, Call 2, Call 3] $3 + R_4$

BINSHAN V K – SREE CHITRA THIRUNAL COLLEGE OF ENGINEERING TRIVANDRUM 12


UCEST105 ALGORITHMIC THINKING WITH PYTHON - SOLVED PYQ

4 multiply_recursive(3, 1) [Call 1, ..., Call 4] $3 + R_5$

5 (Base) multiply_recursive(3, 0) [Call 1, ..., Call 5] 0

Unwind 4 Resolves $3 + 0$ [Call 1, ..., Call 3] 3

Unwind 3 Resolves $3 + 3$ [Call 1, Call 2] 6

Unwind 2 Resolves $3 + 6$ [Call 1] 9

Unwind 1 Resolves $3 + 9$ [Empty] 12

Call Stack Explanation: The call stack grows as each recursive call (from 1 to 4) is pushed onto the
stack. Each frame holds the necessary context (like the return address and local variables) for that
function call to resume when the subsequent call returns. When the base case (Call 5, where $b=0$)
is reached, the recursion stops. The stack then unwinds, meaning the values stored in the stack
frames are processed sequentially from top to bottom, accumulating the results (the additions) until
the initial function call (Call 1) returns the final answer, 12.

Module - 4
15. a) Illustrate the process of sorting the array using the merge sort algorithm. Draw a diagram
showing how the array is split and merged at each stage. (6 Marks)

Merge sort is a Divide and Conquer algorithm that splits the array until single elements remain, and
then merges them back in sorted order.

1. Splitting (Divide Stage): The array is recursively divided into two halves until the sub-arrays
contain only one element. $$

$$ $$ \quad\quad\quad | \quad\quad\quad $$ $$ \quad | \quad \quad || \quad \quad | \quad $$


$$ , \quad | \quad, \quad || \quad, \quad | \quad, $$

2. Merging (Conquer Stage): The sub-arrays are merged in sorted order.

• Merge 1:

o , $\rightarrow$ ``

o , $\rightarrow$ ``

o , $\rightarrow$ ``

o , $\rightarrow$ ``

• Merge 2:

o , $\rightarrow$ ``

o , $\rightarrow$ ``

• Merge 3 (Final Merge):

BINSHAN V K – SREE CHITRA THIRUNAL COLLEGE OF ENGINEERING TRIVANDRUM 13


UCEST105 ALGORITHMIC THINKING WITH PYTHON - SOLVED PYQ

o , $\rightarrow$ ``

15. b) What is memoization, and how does it differ from tabulation in dynamic programming? (3
Marks)

Memoization: Memoization is a technique used in dynamic programming that uses a top-down


approach. It involves implementing a recursive solution but storing (caching) the results of function
calls corresponding to solved subproblems. If the same subproblem is encountered again, the stored
result is returned immediately, avoiding redundant calculations.

Difference from Tabulation:

Feature Memoization Tabulation

Bottom-Up: Starts with the simplest


Top-Down: Starts with the required
Approach subproblems and iteratively builds
solution and recursively breaks it down.
solutions to complex problems.

Uses Recursion with a lookup table (e.g., Uses Iteration (loops) to systematically
Implementation
dictionary or array). fill a table (DP table).

Uses the function call stack heavily, Avoids recursion, relying primarily on
Stack Usage potentially leading to stack overflow loops, and thus generally does not use
issues for extremely deep problems. the call stack for problem solving.

16. a) A vending machine needs to return change to a customer using the least number of coins...
Implement the greedy algorithm to determine the combination of coins that minimizes the total
number of coins used to make a given amount of change. (5 Marks)

The change-making problem, with standard denominations (e.g.,), is optimally solved using the
Greedy Algorithm. The strategy is to always pick the largest coin that is less than or equal to the
remaining amount.

def greedy_change_maker(amount, denominations):

# Denominations must be sorted descendingly for the greedy choice to work

denominations.sort(reverse=True)

change_count = {}

remaining_amount = amount

total_coins = 0

for coin in denominations:

if remaining_amount >= coin:

# 1. Determine the maximum number of times this coin can be used

BINSHAN V K – SREE CHITRA THIRUNAL COLLEGE OF ENGINEERING TRIVANDRUM 14


UCEST105 ALGORITHMIC THINKING WITH PYTHON - SOLVED PYQ

count = remaining_amount // coin

# 2. Record the usage

change_count[coin] = count

total_coins += count

# 3. Update the remaining amount for the next iteration

remaining_amount %= coin

if remaining_amount == 0:

return change_count, total_coins

else:

# This occurs if the denominations cannot make the exact change (not an issue here)

return "Cannot make exact change.", -1

# Example Use Case: 63 cents with standard US coins

coins =

result, count = greedy_change_maker(63, coins)

# Example Trace:

# 63 cents: Uses 2 x 25 cents (Remaining 13)

# 13 cents: Uses 1 x 10 cents (Remaining 3)

# 3 cents: Uses 0 x 5 cents (Remaining 3)

# 3 cents: Uses 3 x 1 cent (Remaining 0)

# Total coins used: 2 + 1 + 3 = 6

BINSHAN V K – SREE CHITRA THIRUNAL COLLEGE OF ENGINEERING TRIVANDRUM 15


UCEST105 ALGORITHMIC THINKING WITH PYTHON - SOLVED PYQ

16. b) Compare Greedy Algorithms and Dynamic Programming in terms of their approach, solution
guarantee, and applicable scenarios. Provide examples where each approach is preferred. (4
Marks)

Feature Greedy Algorithms Dynamic Programming (DP)

Global Optimization: Solves problems by


Local Optimization: Makes the best
ensuring that the optimal solution to the large
Approach choice at the current step without
problem is built from the optimal solutions of
considering future outcomes.
its subproblems.

Does not guarantee optimality for all


Guarantees optimality for problems with
Solution problems. Works only when the
optimal substructure and overlapping
Guarantee problem has the "greedy choice
subproblems.
property".

Preferred for complex optimization problems


Preferred when fast, simple solutions
Applicable where intermediate results must be cached
are needed, and the greedy choice
Scenarios and reused to avoid exponential time
property holds.
complexity.

Preferred: Standard currency change- Preferred: 0/1 Knapsack Problem, Matrix Chain
Examples making, Minimum Spanning Trees Multiplication, Fibonacci sequence calculation
(e.g., Prim's algorithm). (efficiently).

Analogy to Clarify: Think of the difference between Dynamic Programming and the Brute Force
approach (which recursion often embodies) as navigating a maze. Brute Force is like exploring every
single dead-end path repeatedly whenever you reach a junction. Dynamic Programming is like
navigating the maze and, every time you reach a junction you've been to before, you immediately
know the outcome of that path without having to walk it again, thanks to a mental map (the cache
or DP table) you built along the way. This drastically speeds up finding the exit.

BINSHAN V K – SREE CHITRA THIRUNAL COLLEGE OF ENGINEERING TRIVANDRUM 16

You might also like