Python Case Study Questions with Answers
Python Case Study Questions with Answers
Answer:
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
Answer:
def gcd(a, b):
while b:
a, b = b, a % b
return a
Question: Write a Python program to check if a given number is prime using trial
division.
Answer:
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
Question: Write a Python program to find the sum of digits of a given integer
using recursion.
Answer:
def sum_of_digits(n):
if n == 0:
return 0
else:
return n % 10 + sum_of_digits(n // 10)
num = int(input("Enter an integer: "))
print("Sum of digits:", sum_of_digits(num))
Question: Write a Python program to implement the merge sort algorithm to sort
a list of integers.
Answer:
ef merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
merge_sort(left_half)
merge_sort(right_half)
i=j=k=0
while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
arr[k] = left_half[i]
i += 1
else:
arr[k] = right_half[j]
j += 1
k += 1
while i < len(left_half):
arr[k] = left_half[i]
i += 1
k += 1
while j < len(right_half):
arr[k] = right_half[j]
j += 1
k += 1