Practice
Practice
1. Recall the problem in lab 3 where you determined the minimum number of bags required to pack three
watermelons of weight w1, w2, w3 (without cutting them), into bags that can carry a maximum weight
of W, where W ≥ max(w1, w2, w3).
(a) Give an instance, that is, values of w1, w2, w3, W, for which the minimum number of bags needed
is not equal to the ceiling of (w1 + w2 + w3)/W.
(b) Suppose now that we have to pack n watermelons whose weight have been given in an increasing
order in the list weights into n − 1 bags of capacity W. Complete the following function that
returns True if this is possible, and False otherwise.
def pack(weights, W):
________
________
________
________
(c) Suppose now that the weights of n watermelons is given as a list weights, where weights[i] is
the weight of the i’th watermelon. The weights are not necessarily arranged in increasing order.
A vendor packs these watermelons as follows: starting from an empty bag of capacity W, put
watermelons 0, 1, 2, . . . until the bag cannot hold the next watermelon. Write a function that
returns the number of watermelons put into the bag.
def singlebag(weights, W)
________
________
________
________
(d) Suppose now that the vendor packs watermelons as above, but needs to pack all the n watermelons.
Whenever the current bag can’t hold the next watermelon, the vender gives the bag to the
customer and starts putting watermelons into a new bag. Write a function that returns the
number of bags used in this process.
def greedypack(weights, W):
________
________
________
________
(Ashish Chiplunkar)
2. Recall the problem from lab 3 related to the Collatz conjecture: you were asked to write a function
to determine the number of many times the function f defined below needs to be applied to a given
number n so that it becomes 1:
(
n/2 if n is even
f (n) =
3n + 1 otherwise.
Let c(n) denote the minimum number m such that f m (n) = 1, where f m denotes f applied n times.
(In the lab, you were asked to write a function that, given n, computes c(n).) Write a function that,
given argument M , returns the minimum number N such that c(N ) ≥ M . For example, note that
c(1) = 0 < 4, c(2) = 1 < 4, and c(3) ≥ 3, because f (f (f (3))) = f (f (10)) = f (5) = 16 ̸= 1. Thus, on
input 4, your function must return 3.
def min_collatz(m):
________
________
________
________
COL100-Diwali2024 Practice Problems
(Ashish Chiplunkar)
3. We often want to convert a raw measurement expressed in one unit into a human-readable form using
a combination of large and small units. For example, it is easier to understand a height of 64 inches
as ’5 feet 4 inches’, and a duration of 106 seconds as ’11 days 13 hours 46 minutes 40 seconds’. In this
format, the number of each unit must be less than the size of the next larger unit (e.g. it would not
be valid to say ’4 feet 16 inches’, because 16 inches ≥ 1 foot). Suppose that you are given two lists
specifying the names of the units and their conversion factors, for example
Interpret a factor of zero to mean that there are no higher units to convert to. With these lists, for
example, an input of 3602 should be converted to ’1 hours 0 minutes 2 seconds’ or ’1 hours 2 seconds’
(either is acceptable).
Design a recursive function that converts an integer n of the smallest unit to a human readable string
using the lists names and factor.
(Nischay Diwan)
4. A proper divisor of a natural number n is any natural number that divides n other than n itself. We
call a pair (m, n) of numbers amicable if their proper divisors add up to each other. For example, 220
and 284 are amicable because 1 + 2 + 4 + 5 + 10 + 11 + 20 + 22 + 44 + 55 + 110 = 284 and 1 +
2 + 4 + 71 + 142 = 220. Write a clean function that takes two integer parameters and returns True
if they are amicable, and False otherwise.
(Nischay Diwan)
5. Consider the following function definition.
def func(n):
count = 0
m = 1 # line 3
while m < n:
m = 3*m # line 5
count = count+1
return count
(b) Write a function that takes a list parameter managers that represents a hierarchy, and returns
the maximum number of employees managed by any employee.
(Ashish Chiplunkar)
7. Consider the following recursive function that takes as parameter a list of integers and returns an
integer.
def process(l):
n = len(l)
if n == 0:
return 0
elif n == 1:
return l[0]%2024
else:
mid = n//2
ans0 = process(l[:mid])
ans1 = process(l[mid:])
return (ans0+ans1)%2024
Suppose that python has an unbounded amount of memory for its scope stack, so RecursionError is
never thrown.
(a) Prove that for every list l of integers, the above call returns some value after a finite amount of
time, that is, doesn’t go into an infinite recursion.
(b) Determine the value returned by the call process(l) for an arbitrary list l of integers. Prove
your answer.
(Ashish Chiplunkar)
8. Consider the following code that intends to remove multiples of 3 from a list and add them to another
list.
A = [2, 1, 6, 9, 5]
B = A
C = []
for x in A:
if( x % 3 == 0):
A.remove(x)
C.append(x)
print(A)
print(B)
print(C)
Write the output, explaining why was it generated. Can you find some problem with this code? If
yes, rewrite the correct code. (Nischay Diwan)
9. Recall the problem in lab 6 where we found the value of a polynomial at a given value for the variable.
Given a polynomial P (x) as an input and a particular value of the variable (say x1 ) , you are asked
to find:
(a) The value of the derivative P ′ (x) at x1
(b) The value of the nth derivative P n (n) at x1
Note: Your inputs would be similar to the problem given in lab 6 i.e., a list of coefficients for P (x)
(Rittik Dey)
COL100-Diwali2024 Practice Problems
10. Assume you are standing in front of staircase containing n steps of unit height (i.e height is 1). Being
an enthusiastic first year UG student, you could jump either 1 or 2 or 3 steps at once, but not more
than that. Now, you wonder, In how many ways can you reach the top most step n, which you call
f (n).
1. Can you describe a recursive formulation for the function f (n), that can be programmed.
2. How many function calls will be made for say, n = 7? It is useful to think in terms of Recursion
tree, where you draw an arrow for each new function call to new function call with parameter.
(Chethan)
11. What would be the output of the following code?
x = 2+5*3%2/2-5*10
print(x)
Note: In Python *, /, //, % (multiplication, division, floor division, remainder) is given the same
priority and higher than that of +, - (addition , subtraction). Also, for arithmetic operations, the
order of evaluation is from left to right!
(Akshat Chaudhary)
12. Bob and Mary are working on a group project and need to implement 2 functions in Python. Their
goal is to implement the functions in an efficient manner so that they can beat their classmates and
not timeout! They have been provided with a list of positive integers sorted in increasing order and
have divided the work among them as follows:
(a) Bob wants to write a function get first index(mylist, num) which will find the index of the
first occurrence of the integer num in a sorted list of positive integers mylist. Can you help Bob
write this function?
# For example
mylist = [1, 1, 1, 2, 3, 3, 4], num = 3
get_first_index(mylist, num) should return 4
(b) Mary wants to write a similar function get last index(mylist, num) which will find the index
of the last occurrence of the integer num in mylist instead of the first occurrence. Can you help
Mary write this function?
# For example
mylist = [1, 1, 1, 2, 3, 3, 4], num = 3
get_last_index(mylist, num) should return 5
(Amaiya)
13. You are given a list of 1s and 0s.Say A = [ 1, 0, 1, 0, 1, 1, 0, 0 ]
If you encounter 3 consecutive 1s, insert a 0 after the 1s.
Eg:
If A = [ 1, 0, 1, 1, 1, 0 ], you should return [ 1, 0, 1, 1, 1, 0, 0 ]
If A = [ 1, 0, 1, 1 ], you should return [ 1, 0, 1, 1 ]
Design an iterative and recursive function in Python to do the task. This will improve your under-
standing between recursive and iterative functions.
def stuff_bit( A ):
________
________
________
________
return A
COL100-Diwali2024 Practice Problems
(Satej)
14. Given a list coins of size N and a target value sum, where coins[i] represents the coins of different
denomination (Assume infinite supply of each type). The task is to find minimum number of coins
required to make the given value sum. If it is not possible to make the given sum, print -1.
Eg:
Input: coins = [9, 6, 5, 1] sum = 19
Output: 3
Input: coins = [5, 1] sum = 0
Output: 0
(Dhruva Bhardwaj)
15. Recall the problem on Collatz length in lab 3: you were asked to write a function to determine the
number of many times the function f defined below needs to be applied to a given number n so that
it becomes 1: (
n/2 if n is even
f (n) =
3n + 1 otherwise.
Write a function sort by collatz(low, high) which sorts all integers in the range [low, high] according
to their Collatz length.
Is there some benefit of using dictionaries over lists for memoization in such problems? Why/why not?
(Akshit Goel)
16. A robot is on the ground floor and wants to reach the first floor by climbing a staircase. Unfortunately,
there are no lifts, so the robot has to climb a staircase consisting of N steps to reach the first floor.
The robot can take either 1 step or 4 steps at a time.
Write a program to calculate the number of distinct ways the robot can reach the first floor.
Input:
A single integer N represents the number of steps in the staircase.
Output:
An integer represents the number of distinct ways the robot can climb N steps.
(C Adithya)
COL100-Diwali2024 Practice Problems
17. You would like to make dessert and are preparing to buy the ingredients. You have n ice cream base
flavors and m types of toppings to choose from. You must follow these rules when making your dessert:
(a) There must be exactly one ice cream base.
(b) You can add one or more types of topping or have no toppings at all.
(c) There are at most two of each type of topping.
Your program should accept three inputs:
baseCosts, an integer array of length n, where each
baseCosts[i] represents the price of the ith ice cream base flavor.
toppingCosts, an integer array of length m, where each toppingCosts[i] is the price of one of the
ith topping.
target, an integer representing your target price for dessert. You want to make a dessert with a total
cost as close to target as possible.
Return the closest possible cost of the dessert to target. If there are multiple, return the lower one.
Example 1:
Input: baseCosts = [1,7], toppingCosts = [3,4], target = 10
Output: 10
Explanation: Consider the following combination (all 0-indexed):
- Choose base 1: cost 7
- Take 1 of topping 0: cost 1 x 3 = 3
- Take 0 of topping 1: cost 0 x 4 = 0
- Total: 7 + 3 + 0 = 10
Example 2:
Input: baseCosts = [2,3], toppingCosts = [4,5,100], target = 18
Output: 17
Explanation: Consider the following combination (all 0-indexed):
- Choose base 1: cost 3
- Take 1 of topping 0: cost 1 x 4 = 4
- Take 2 of topping 1: cost 2 x 5 = 10
- Take 0 of topping 2: cost 0 x 100 = 0
- Total: 3 + 4 + 10 + 0 = 17.
You cannot make a dessert with a total cost of 18.
(Parthasaradhi N)
18. Recall Problem 5 of Lab 5 - Take Home, famously known as the Edit Distance problem (Try solving
it first, before jumping on this problem!)
if m == 0:
return n
"""
If second string is empty, the only option is to
remove all characters of first string
"""
#Base Case 2
if n == 0:
return m
"""
If last characters of two strings are same, nothing
much to do. Ignore last characters and get count for
remaining strings.
"""
if s1[m-1] == s2[n-1]:
return edit(s1, s2, m-1, n-1)
"""
If last characters are not same, consider all three
operations on last character of first string, recursively
compute minimum cost for all three operations and take
minimum of three values.
"""
return ( 1 + min(edit(s1, s2, m, n-1), # Insert
edit(s1, s2, m-1, n), # Remove
edit(s1, s2, m-1, n-1)) # Replace
)
19. If you recall problem 2 from Lab 9, we searched for all the files inside a folder by using the crawl
function. We would try to solve the classical maze problem using the same idea. We can for example
plan our path in a maze by recursing over the paths and backtracking from the ones that lead nowhere.
This of course requires us to represent the maze in a way that the algorithm is compatible with. A
common method is to use a 2-d matrix and values within it to represent obstacles or paths. Given
an N × N matrix A of blocks where the upper-most left (0, 0) block acts as your starting point, we
want to find a path from the start to the destination, the lower-most right block (N − 1, N − 1). A
walk-able cell of the matrix is indicated by 1 and a wall is indicated by 0 as an entry of the given
matrix A[][]. A path is a sequence of adjacent cells, where we call two cells adjacent if they are in the
same row and adjacent columns, or in the same column and adjacent rows. Design a program to solve
the maze problem:
COL100-Diwali2024 Practice Problems
Examples:
1) Input: skills = [2, 5, 3, 7, 4, 8, 6]
Output: 4
Explanation: The longest increasing sequence of difficulties you can complete is [2, 3, 4, 8], representing
a progression of 4 skills.
2) Input: skills = [10, 22, 9, 33, 21, 50, 41, 60, 80]
Output: 6
Explanation: The longest increasing sequence of skill difficulties is [10, 22, 33, 50, 60, 80], with a
progression length of 6 skills.
(Anand Sharma)