L17 Recursion Practice Set (Questions)
L17 Recursion Practice Set (Questions)
L17 Recursion Practice Set (Questions)
Practice/Tutorial Questions:
print(mystery(5))
countdown(3)
zigzag(3)
7. How many times will the base case execute if nested_calls(4) is called?
def nested_calls(n):
if n == 0:
return 1
nested_calls(n - 1)
nested_calls(n - 1)
nested_calls(4)
Programming Questions:
1. Sum of Digits (Trick with Negative Numbers): Write a recursive function
that computes the sum of digits of an integer n. Handle cases where the
number is negative and ensure the recursive function works properly.
Test cases:
Input1: 123
Output1: 6
Input2: -123
Output2 : 6
Output:
c
b
bc
a
ac
ab
abc
Test case 1:
String: hello world
Character: o
Output: 2
Test case 2:
String: abcabcabc
Character: b
Output: 3
● Parentheses ( and ).
● Variables (e.g., a, b, x), digits, and operators (e.g., +, -, *, /).
test_cases = [
Constraints:
The string s contains at most 10^5 characters and only valid characters
(parentheses, digits, operators, and variables).
2. The Subset Sum Problem: You are tasked with helping a store manager
organize a promotional sale. The store has a collection of products, each with
a specific price, and the manager wants to know if there exists a combination
of products that can be purchased for exactly a target budget.
Write a recursive function that takes a list of product prices and a target
budget as input. The function should return one subset of products whose
total price equals the target budget. If no such combination exists, return an
appropriate message.
For example:
● Given the list of product prices [3, 34, 4, 12, 5, 2] and a target
budget of 9, the function should output a subset like [4, 5], as 4 +
5 = 9.
● If the target budget is not achievable, print No subset found for
the given budget.
Test case 1:
target = 9
find_subset_sum(nums, target)
# Output: Subset that forms the sum: [4, 5]
Test case 2:
target = 30
find_subset_sum(nums, target)