Programming assignment - Week 6
Programming assignment - Week 6
Solutions
Note: There could be optimised ways to solve the problem, but the goal here is to solve it effectively. The most intuitive solution has been provided for clarity.
Programming assignment - 1
Write a Python program that takes two positive integers a and b as input and returns their product using a recursive function. The function should only use the + and - operators to calculate the product.
Input Format:
The first line of input consists of two space-separated positive integers, a and b.
Output Format:
The output consists of a single integer representing the product of a and b.
Example:
Input:
3 4
Output:
12
Code:
def recursive_multiply(a, b):
# Base case: if b is 0, the product is 0
if b == 0:
return 0
# Recursive case: add 'a' to the product of 'a' and 'b - 1'
return a + recursive_multiply(a, b - 1)
# Read input from the user
a, b = map(int, input().split())
# Call the recursive function and print the result
print(recursive_multiply(a, b), end="")
Programming assignment - 2
Write a Python program that takes a positive integer x as input and returns the logarithm of x to the base 2 using a recursive function. The logarithm of x to the base 2, denoted by log₂(x), is the number of times 2 has to be multiplied by itself to get x. Assume that x is a power of 2.
Input Format:
The input consists of a single positive integer x which is a power of 2.
Output Format:
The output consists of a single integer representing log₂(x).
Example:
Input:
8
Output:
3
Code:
def recursive_log2(x):
if x == 1:
return 0
return 1 + recursive_log2(x // 2)
x = int(input())
print(recursive_log2(x), end="")
Programming assignment - 3
Write a Python program that includes a recursive function named non_decreasing which takes a non-empty list L of integers as input. The function should return True if the elements in the list are sorted in non-decreasing order from left to right, and False otherwise.
Input Format:
The input consists of a single line containing space-separated integers that form the list L.
Output Format:
The output consists of a single boolean value (True or False) indicating whether the list is sorted in non-decreasing order.
Example:
Input: 1 2 2 3 4
Output: True
Code:
def non_decreasing(L):
# Base case: A list with one element or an empty list is sorted
if len(L) <= 1:
return True
# Recursive case: Check if the first element is less than or equal to the second
# and then check the rest of the list
return L[0] <= L[1] and non_decreasing(L[1:])
# Read input from the user
L = list(map(int, input().split()))
# Call the recursive function and print the result
print(non_decreasing(L), end="")
Comments
Post a Comment