Question 1: Sum of Digits of a Number
def sum_of_digits(n):
n = abs(n)
total = 0
while n > 0:
total += n % 10
n = n // 10
return total
Question 2: Check if a Number is Prime
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 3: Factorial of a Number Using Recursion
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
Question 4: Find the Greatest Common Divisor (GCD) of Two Numbers
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
Question 5: Count Vowels in a String
def count_vowels(s):
vowels = 'aeiouAEIOU'
count = 0
for char in s:
if char in vowels:
count += 1
return count
Question 6: Fibonacci Sequence Using Recursion
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
Question 7: Find the Second Largest Number in a List
def second_largest(lst):
first = second = float('-inf')
for num in lst:
if num > first:
second = first
first = num
elif num > second and num != first:
second = num
return second
Question 8: Palindrome Check
def is_palindrome(s):
s = s.lower().replace(" ", "")
return s == s[::-1]
Question 9: Reverse Words in a String
def reverse_words(sentence):
words = sentence.split()
reversed_words = words[::-1]
return ' '.join(reversed_words)
Question 10: Remove Duplicates from a List
def remove_duplicates(lst):
return list(set(lst))