Function For MidTerm
Function For MidTerm
HMI-Batch 5
1. Factorial Calculation
Solution
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
2. Fibonacci Sequence
Write a function that returns the n-th Fibonacci number using recursion.
Solution
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
print(fibonacci(6)) # Output: 8
Solution
def is_prime(n):
if n < 2:
return False
if n % i == 0:
return False
return True
Write a function to compute the GCD of two numbers using recursion (Euclidean Algorithm).
Solution
while b != 0:
return a
5. Sum of Digits
Write a function that calculates the sum of the digits of a given number recursively.
Solution
def sum_of_digits(n):
total = 0
while n > 0:
return total
print(sum_of_digits(1234)) # Output: 10
6. Matrix Multiplication
Solution
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
return result
print(matrix_multiply(A, B))
Solution
def binary_to_decimal(binary_str):
return int(binary_str, 2)
print(binary_to_decimal("1011")) # Output: 11
8. Compute nCr (Combinations Formula)
Solution
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
Write a function to find the missing number in a list of n-1 numbers from 1 to n.
Solution
def find_missing_number(nums):
n = len(nums) + 1
expected_sum = n * (n + 1) // 2
actual_sum = sum(nums)
Solution
def count_vowels(s):
count = 0
if char in "aeiou":
count += 1
return count
Solution
def is_prime(n):
if n < 2:
return False
if n % i == 0:
return False
return True
Solution
# Example usage:
nums = [10, 20, 30, 40, 50]
target = int(input("Enter the number to search for: "))
result = linearSearch(nums, target)
if result != -1:
print(f"The number {target} is at position {result}.")
else:
print(f"The number {target} is not in the list.")