1. Find the Sum of Natural Numbers Using Recursion:
def sum_of_natural_numbers(n):
if n <= 1:
return n
else:
return n + sum_of_natural_numbers(n - 1)
num = int(input("Enter a number: "))
print("Sum of natural numbers:", sum_of_natural_numbers(num))
2. Validate an IP Address:
import socket
def is_valid_ip(ip):
try:
socket.inet_aton(ip)
return True
except socket.error:
return False
ip_address = input("Enter an IP address: ")
if is_valid_ip(ip_address):
print("Valid IP address")
else:
print("Invalid IP address")
3. Calculate the Greatest Common Divisor (GCD) Using Recursion:
def gcd(x, y):
if y == 0:
return x
else:
return gcd(y, x % y)
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print("GCD:", gcd(num1, num2))
4. Implement a Queue using a List:
class Queue:
def __init__(self):
self.items = []
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
if self.items:
return self.items.pop()
return None
def is_empty(self):
return self.items == []
queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
print("Dequeued item:", queue.dequeue())
print("Queue is empty:", queue.is_empty())
5. Calculate the Power Set of a Set using Iterative Approach:
def power_set_iterative(s):
power_set = [[]]
for elem in s:
for sub_set in power_set[:]:
power_set.append(sub_set + [elem])
return power_set
input_set = [1, 2, 3]
print("Power set (iterative):", power_set_iterative(input_set))
6. Print the Calendar of a Given Month and Year:
import calendar
year = int(input("Enter the year: "))
month = int(input("Enter the month: "))
print(calendar.month(year, month))
7. Find the Median of Three Values:
def find_median(a, b, c):
return sorted([a, b, c])[1]
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))
print("Median:", find_median(num1, num2, num3))
8. Implement a Binary Search Algorithm Using Recursion:
def binary_search_recursive(arr, low, high, x):
if high >= low:
mid = (high + low) // 2
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binary_search_recursive(arr, low, mid - 1, x)
else:
return binary_search_recursive(arr, mid + 1, high, x)
else:
return -1
arr = [2, 3, 4, 10, 40]
x = 10
result = binary_search_recursive(arr, 0, len(arr) - 1, x)
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")
9. Find the Sum of Digits in a Number:
def sum_of_digits(n):
return sum(int(digit) for digit in str(n))
number = int(input("Enter a number: "))
print("Sum of digits:", sum_of_digits(number))
10. Convert Decimal to Binary, Octal, and Hexadecimal:
dec = int(input("Enter a decimal number: "))
print("Binary:", bin(dec))
print("Octal:", oct(dec))
print("Hexadecimal:", hex(dec))
0 Comments