Python Programs

Practice Code Examples

Hands-on Python programs to practice and master programming concepts. From basic to advanced level.

Python 3 ✓ Practice 25+ Programs Interview Prep
01

Basic Programs

#1 Check Prime Number Basic
Python
def is_prime(n):
    if n < 2: return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0: return False
    return True

print(is_prime(17))  # True
print(is_prime(4))   # False
#2 Factorial of a Number Basic
Python
def factorial(n):
    if n == 0 or n == 1: return 1
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

# Using recursion
def factorial_rec(n):
    if n <= 1: return 1
    return n * factorial_rec(n - 1)

print(factorial(5))  # 120
#3 Fibonacci Sequence Basic
Python
def fibonacci(n):
    if n <= 0: return []
    if n == 1: return [0]

    seq = [0, 1]
    for i in range(2, n):
        seq.append(seq[-1] + seq[-2])
    return seq

print(fibonacci(10))  # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
#4 Reverse a String Basic
Python
def reverse_string(s):
    return s[::-1]

# Using two pointers
def reverse_two_ptr(s):
    chars = list(s)
    left, right = 0, len(s) - 1
    while left < right:
        chars[left], chars[right] = chars[right], chars[left]
        left += 1
        right -= 1
    return ''.join(chars)

print(reverse_string("hello"))  # "olleh"
#5 Check Palindrome Basic
Python
def is_palindrome(s):
    s = s.lower().replace(" ", "")
    return s == s[::-1]

# Two pointer approach
def is_palindrome_tp(s):
    left, right = 0, len(s) - 1
    while left < right:
        if s[left] != s[right]: return False
        left += 1
        right -= 1
    return True

print(is_palindrome("A man a plan a canal Panama"))  # True
#15 Print a Message Basic
Python
print("Hello Python")
#16 Addition and Division Basic
Python
# Addition
num1 = float(input("Enter the first number for addition: "))
num2 = float(input("Enter the second number for addition: "))
sum_result = num1 + num2
print(f"Sum: {num1} + {num2} = {sum_result}")

# Division
num3 = float(input("Enter the dividend for division: "))
num4 = float(input("Enter the divisor for division: "))
if num4 == 0:
    print("Error: Division by zero is not allowed.")
else:
    div_result = num3 / num4
    print(f"Division: {num3} / {num4} = {div_result}")
#17 Area of a Triangle Basic
Python
base = float(input("Enter the length of the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))

area = 0.5 * base * height
print(f"The area of the triangle is: {area}")
#18 Swap Two Variables (with Temp) Basic
Python
a = input("Enter the value of the first variable (a): ")
b = input("Enter the value of the second variable (b): ")
print(f"Original values: a = {a}, b = {b}")

temp = a
a = b
b = temp
print(f"Swapped values: a = {a}, b = {b}")
#19 Generate a Random Number Basic
Python
import random

print(f"Random number: {random.randint(1, 100)}")
#20 Kilometers to Miles Converter Basic
Python
kilometers = float(input("Enter distance in kilometers: "))

# Conversion factor: 1 kilometer = 0.621371 miles
conversion_factor = 0.621371
miles = kilometers * conversion_factor

print(f"{kilometers} kilometers is equal to {miles} miles")
#21 Celsius to Fahrenheit Converter Basic
Python
celsius = float(input("Enter temperature in Celsius: "))

# Fahrenheit = (Celsius * 9/5) + 32
fahrenheit = (celsius * 9 / 5) + 32

print(f"{celsius} degrees Celsius is equal to {fahrenheit} degrees Fahrenheit")
#22 Display a Calendar Basic
Python
import calendar

year = int(input("Enter year: "))
month = int(input("Enter month: "))

cal = calendar.month(year, month)
print(cal)
#23 Solve a Quadratic Equation Basic
Python
import math

a = float(input("Enter coefficient a: "))
b = float(input("Enter coefficient b: "))
c = float(input("Enter coefficient c: "))

discriminant = b**2 - 4 * a * c

if discriminant > 0:
    root1 = (-b + math.sqrt(discriminant)) / (2 * a)
    root2 = (-b - math.sqrt(discriminant)) / (2 * a)
    print(f"Root 1: {root1}")
    print(f"Root 2: {root2}")
elif discriminant == 0:
    root = -b / (2 * a)
    print(f"Root: {root}")
else:
    real_part = -b / (2 * a)
    imaginary_part = math.sqrt(abs(discriminant)) / (2 * a)
    print(f"Root 1: {real_part} + {imaginary_part}i")
    print(f"Root 2: {real_part} - {imaginary_part}i")
#24 Swap Two Variables (without Temp) Basic
Python
a = 5
b = 10

# Swapping without a temporary variable
a, b = b, a

print("After swapping:")
print("a =", a)
print("b =", b)
#25 Check Positive, Negative or Zero Basic
Python
num = float(input("Enter a number: "))

if num > 0:
    print("Positive number")
elif num == 0:
    print("Zero")
else:
    print("Negative number")
#26 Check Odd or Even Basic
Python
num = int(input("Enter a number: "))

if num % 2 == 0:
    print("This is an even number")
else:
    print("This is an odd number")
#27 Check Leap Year Basic
Python
year = int(input("Enter a year: "))

if (year % 400 == 0) and (year % 100 == 0):
    print(f"{year} is a leap year")
elif (year % 4 == 0) and (year % 100 != 0):
    print(f"{year} is a leap year")
else:
    print(f"{year} is not a leap year")
#28 Print Primes in an Interval Basic
Python
lower, upper = 1, 10

for num in range(lower, upper + 1):
    if num > 1:
        for i in range(2, num):
            if num % i == 0:
                break
        else:
            print(num)
# Output: 2 3 5 7
#29 Multiplication Table Basic
Python
num = int(input("Enter a number: "))

for i in range(1, 11):
    print(f"{num} x {i} = {num * i}")
# 5 x 1 = 5 ... 5 x 10 = 50
#30 Check Armstrong Number Basic
Python
num = int(input("Enter a number: "))
order = len(str(num))

total = sum(int(d) ** order for d in str(num))

if num == total:
    print(f"{num} is an Armstrong number")
else:
    print(f"{num} is not an Armstrong number")
# 153 = 1^3 + 5^3 + 3^3 = 153  -> Armstrong
#31 Armstrong Numbers in an Interval Basic
Python
lower, upper = 1, 1000

for num in range(lower, upper + 1):
    order = len(str(num))
    if num == sum(int(d) ** order for d in str(num)):
        print(num)
# Output: 1 2 3 4 5 6 7 8 9 153 370 371 407
#32 Sum of Natural Numbers Basic
Python
n = int(input("Enter n: "))

# Loop approach
total = 0
for i in range(1, n + 1):
    total += i
print(total)

# Formula approach: n(n+1)/2
print(n * (n + 1) // 2)  # same result, O(1)
#33 Find LCM of Two Numbers Basic
Python
def lcm(a, b):
    greater = max(a, b)
    while True:
        if greater % a == 0 and greater % b == 0:
            return greater
        greater += 1

print(lcm(4, 6))  # 12
#34 Find HCF (GCD) of Two Numbers Basic
Python
def hcf(a, b):
    # Euclidean algorithm
    while b:
        a, b = b, a % b
    return a

print(hcf(54, 24))  # 6
#35 Decimal to Binary, Octal, Hexadecimal Basic
Python
num = int(input("Enter a decimal number: "))

print(bin(num))  # 0b101010
print(oct(num))  # 0o52
print(hex(num))  # 0x2a
#36 ASCII Value of a Character Basic
Python
ch = input("Enter a character: ")

print(f"ASCII value of {ch} is {ord(ch)}")
print(f"Character for 65 is {chr(65)}")  # A
#37 Simple Calculator Basic
Python
def calculator():
    a = float(input("First number: "))
    op = input("Operator (+ - * /): ")
    b = float(input("Second number: "))

    if op == '+': return a + b
    if op == '-': return a - b
    if op == '*': return a * b
    if op == '/':
        if b == 0: return "Cannot divide by zero"
        return a / b
    return "Invalid operator"

print(calculator())
#38 Body Mass Index (BMI) Calculator Basic
Python
weight = float(input("Weight in kg: "))
height = float(input("Height in metres: "))

bmi = weight / (height ** 2)
print(f"BMI: {bmi:.1f}")

if bmi < 18.5:   print("Underweight")
elif bmi < 25:   print("Normal weight")
elif bmi < 30:   print("Overweight")
else:            print("Obese")
#39 Natural Logarithm of a Number Basic
Python
import math

num = float(input("Enter a positive number: "))

print(f"ln({num}) = {math.log(num)}")
print(f"log10({num}) = {math.log10(num)}")
print(f"log2({num}) = {math.log2(num)}")
#40 Cube Sum of First N Natural Numbers Basic
Python
def cube_sum(n):
    return sum(i ** 3 for i in range(1, n + 1))

# Formula: (n(n+1)/2)^2
def cube_sum_formula(n):
    return (n * (n + 1) // 2) ** 2

print(cube_sum(5))          # 225
print(cube_sum_formula(5))  # 225
#41 Check Disarium Number Basic
Python
def is_disarium(num):
    # Sum of digits raised to their positions equals the number
    digits = str(num)
    total = sum(int(d) ** (i + 1) for i, d in enumerate(digits))
    return total == num

print(is_disarium(135))  # True: 1^1 + 3^2 + 5^3 = 135
print(is_disarium(80))   # False
#42 Disarium Numbers Between 1 and 100 Basic
Python
def is_disarium(num):
    digits = str(num)
    return num == sum(int(d) ** (i + 1) for i, d in enumerate(digits))

for n in range(1, 101):
    if is_disarium(n):
        print(n)
# Output: 1 2 3 4 5 6 7 8 9 89
#43 Check Happy Number Basic
Python
def is_happy(num):
    # Repeatedly replace with sum of squares of digits;
    # happy if the process reaches 1
    seen = set()
    while num != 1 and num not in seen:
        seen.add(num)
        num = sum(int(d) ** 2 for d in str(num))
    return num == 1

print(is_happy(19))  # True: 1+81=82, 64+4=68, 36+64=100, 1
print(is_happy(4))   # False
#44 Happy Numbers Between 1 and 100 Basic
Python
def is_happy(num):
    seen = set()
    while num != 1 and num not in seen:
        seen.add(num)
        num = sum(int(d) ** 2 for d in str(num))
    return num == 1

print([n for n in range(1, 101) if is_happy(n)])
# [1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100]
#45 Check Harshad Number Basic
Python
def is_harshad(num):
    # Divisible by the sum of its own digits
    digit_sum = sum(int(d) for d in str(num))
    return num % digit_sum == 0

print(is_harshad(18))  # True: 18 % (1+8) == 0
print(is_harshad(19))  # False
#46 Pronic Numbers Between 1 and 100 Basic
Python
def is_pronic(num):
    # Product of two consecutive integers: n*(n+1)
    n = 0
    while n * (n + 1) < num:
        n += 1
    return n * (n + 1) == num

print([x for x in range(1, 101) if is_pronic(x)])
# [2, 6, 12, 20, 30, 42, 56, 72, 90]
02

Intermediate Programs

#6 Binary Search Intermediate
Python
def binary_search(arr, target):
    left, right = 0, len(arr) - 1

    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

arr = [1, 3, 5, 7, 9, 11]
print(binary_search(arr, 7))  # 3
print(binary_search(arr, 2))  # -1
#7 Bubble Sort Intermediate
Python
def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        swapped = False
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                swapped = True
        if not swapped:
            break
    return arr

arr = [64, 34, 25, 12, 22, 11, 90]
print(bubble_sort(arr))  # [11, 12, 22, 25, 34, 64, 90]
#8 Count Word Frequency Intermediate
Python
def word_frequency(text):
    words = text.lower().split()
    freq = {}
    for word in words:
        word = ''.join(c for c in word if c.isalnum())
        if word:
            freq[word] = freq.get(word, 0) + 1
    return freq

# Using Counter
from collections import Counter
def word_freq_counter(text):
    words = text.lower().split()
    return Counter(words)

text = "hello world hello python world"
print(word_frequency(text))
#9 Linked List Implementation Intermediate
Python
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def append(self, data):
        new_node = Node(data)
        if not self.head:
            self.head = new_node
            return
        current = self.head
        while current.next:
            current = current.next
        current.next = new_node

    def display(self):
        elements = []
        current = self.head
        while current:
            elements.append(current.data)
            current = current.next
        return " -> ".join(map(str, elements))

ll = LinkedList()
ll.append(1)
ll.append(2)
ll.append(3)
print(ll.display())  # 1 -> 2 -> 3
#47 Sum of Array Elements Intermediate
Python
arr = [10, 20, 30, 40, 50]

# Manual loop
total = 0
for x in arr:
    total += x
print(total)      # 150

# Built-in
print(sum(arr))   # 150
#48 Largest Element in an Array Intermediate
Python
def find_largest(arr):
    largest = arr[0]
    for x in arr:
        if x > largest:
            largest = x
    return largest

arr = [10, 45, 22, 89, 3]
print(find_largest(arr))  # 89
print(max(arr))           # 89 (built-in)
#49 Rotate an Array by D Positions Intermediate
Python
def rotate_array(arr, d):
    d = d % len(arr)          # handle d > len
    return arr[d:] + arr[:d]

arr = [1, 2, 3, 4, 5, 6, 7]
print(rotate_array(arr, 2))  # [3, 4, 5, 6, 7, 1, 2]
#50 Split Array and Add First Part to End Intermediate
Python
def split_and_move(arr, k):
    return arr[k:] + arr[:k]

arr = [12, 10, 5, 6, 52, 36]
print(split_and_move(arr, 2))
# [5, 6, 52, 36, 12, 10]
#51 Check if Array is Monotonic Intermediate
Python
def is_monotonic(arr):
    increasing = all(arr[i] <= arr[i+1] for i in range(len(arr)-1))
    decreasing = all(arr[i] >= arr[i+1] for i in range(len(arr)-1))
    return increasing or decreasing

print(is_monotonic([1, 2, 2, 3]))   # True
print(is_monotonic([6, 5, 4, 4]))   # True
print(is_monotonic([1, 3, 2]))      # False
#52 Multiply All Numbers in a List Intermediate
Python
import math

numbers = [2, 3, 4, 5]

# Manual loop
product = 1
for x in numbers:
    product *= x
print(product)             # 120

print(math.prod(numbers))  # 120 (Python 3.8+)
#53 Smallest Number in a List Intermediate
Python
numbers = [34, 12, 89, 5, 67]

smallest = numbers[0]
for x in numbers:
    if x < smallest:
        smallest = x
print(smallest)      # 5
print(min(numbers))  # 5 (built-in)
#54 Second Largest Number in a List Intermediate
Python
numbers = [10, 45, 22, 89, 67]

unique = list(set(numbers))
unique.sort()
print(unique[-2])  # 67

# Single pass, no sort
first = second = float('-inf')
for x in numbers:
    if x > first:
        first, second = x, first
    elif first > x > second:
        second = x
print(second)  # 67
#55 N Largest Elements from a List Intermediate
Python
import heapq

numbers = [4, 90, 21, 45, 78, 3, 56]

print(heapq.nlargest(3, numbers))   # [90, 78, 56]
print(sorted(numbers, reverse=True)[:3])  # same idea
#56 Even Numbers in a List Intermediate
Python
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

evens = [x for x in numbers if x % 2 == 0]
print(evens)  # [2, 4, 6, 8, 10]
#57 Odd Numbers in a List Intermediate
Python
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

odds = [x for x in numbers if x % 2 != 0]
print(odds)  # [1, 3, 5, 7, 9]
#58 Remove Empty Lists from a List Intermediate
Python
data = [[1, 2], [], [3], [], [4, 5], []]

cleaned = [x for x in data if x]  # empty list is falsy
print(cleaned)  # [[1, 2], [3], [4, 5]]
#59 Clone or Copy a List Intermediate
Python
original = [1, 2, 3, 4, 5]

copy1 = original[:]          # slice
copy2 = list(original)       # constructor
copy3 = original.copy()      # method

import copy
deep = copy.deepcopy(original)  # for nested lists

copy1.append(6)
print(original)  # [1, 2, 3, 4, 5] — unchanged
#60 Count Occurrences of an Element Intermediate
Python
numbers = [1, 2, 3, 2, 4, 2, 5, 2]

print(numbers.count(2))  # 4

# Count everything at once
from collections import Counter
print(Counter(numbers))
# Counter({2: 4, 1: 1, 3: 1, 4: 1, 5: 1})
#61 Filter Integers from a Mixed List Intermediate
Python
def filter_integers(lst):
    return [x for x in lst if isinstance(x, int)]

mixed = [1, 'a', 2, 'b', 3.5, 4, 'c']
print(filter_integers(mixed))  # [1, 2, 4]

# Note: isinstance(True, int) is True in Python —
# add `and not isinstance(x, bool)` to exclude booleans
#62 Unpack a List into Variables Intermediate
Python
lst = [1, 2, 3, 4, 5, 6]

a, b, *rest = lst
print(a, b)    # 1 2
print(rest)    # [3, 4, 5, 6]

first, *middle, last = lst
print(middle)  # [2, 3, 4, 5]
#63 Move All of One Element Type to the End Intermediate
Python
def move_to_end(lst, el):
    return [x for x in lst if x != el] + [x for x in lst if x == el]

print(move_to_end([1, 3, 2, 4, 4, 1], 1))
# [3, 2, 4, 4, 1, 1]
print(move_to_end(['a', 'a', 'a', 'b'], 'a'))
# ['b', 'a', 'a', 'a']
#64 Find the Missing Number (1 to 10) Intermediate
Python
def missing_num(lst):
    return sum(range(1, 11)) - sum(lst)

print(missing_num([1, 2, 3, 4, 6, 7, 8, 9, 10]))  # 5

# General: expected sum n(n+1)/2 minus actual sum
#65 Append and Shift a List Intermediate
Python
def next_in_line(lst, num):
    if not lst:
        return 'No list has been selected'
    lst.append(num)
    lst.pop(0)
    return lst

print(next_in_line([5, 6, 7, 8, 9], 1))  # [6, 7, 8, 9, 1]
print(next_in_line([], 6))               # No list has been selected
#66 Sort a List and Remove Duplicates Intermediate
Python
def unique_sort(lst):
    return sorted(set(lst))

print(unique_sort([1, 2, 4, 3]))        # [1, 2, 3, 4]
print(unique_sort([1, 4, 4, 4, 4]))     # [1, 4]
print(unique_sort([5, 4, 3, 2, 1]))     # [1, 2, 3, 4, 5]
#67 Find the Unique Number in a List Intermediate
Python
def find_unique(lst):
    for x in set(lst):
        if lst.count(x) == 1:
            return x

print(find_unique([3, 3, 3, 7, 3, 3]))     # 7
print(find_unique([0, 0, 0.77, 0, 0]))     # 0.77
#68 Sort Strings by Length Intermediate
Python
def sort_by_length(words):
    return sorted(words, key=len)

print(sort_by_length(['Google', 'Apple', 'Microsoft']))
# ['Apple', 'Google', 'Microsoft']
print(sort_by_length(['Leonardo', 'Michelangelo', 'Raphael', 'Donatello']))
# ['Raphael', 'Leonardo', 'Donatello', 'Michelangelo']
#69 Sort Words in Alphabetic Order Intermediate
Python
sentence = input("Enter a sentence: ")

words = sentence.split()
words.sort(key=str.lower)

for word in words:
    print(word)
# 'the quick Brown fox' -> Brown fox quick the
#70 Remove Punctuation from a String Intermediate
Python
import string

text = "Hello!!!, he said ---and went."

cleaned = ''.join(ch for ch in text if ch not in string.punctuation)
print(cleaned)  # Hello he said and went
#71 Words Longer Than Length K Intermediate
Python
def find_words(words, k):
    return [w for w in words if len(w) > k]

words = ['apple', 'cat', 'banana', 'dog', 'elephant']
print(find_words(words, 3))
# ['apple', 'banana', 'elephant']
#72 Remove a Character from a String Intermediate
Python
text = "programming"

# Remove all occurrences
print(text.replace('m', ''))    # prograing

# Remove character at index i
i = 3
print(text[:i] + text[i+1:])    # proramming
#73 Split and Join a String Intermediate
Python
sentence = "Python is fun to learn"

words = sentence.split()         # split on whitespace
print(words)   # ['Python', 'is', 'fun', 'to', 'learn']

joined = '-'.join(words)
print(joined)  # Python-is-fun-to-learn
#74 Check if a String is Binary Intermediate
Python
def is_binary(s):
    return set(s) <= {'0', '1'}

print(is_binary('101010'))  # True
print(is_binary('101201'))  # False
#75 Uncommon Words from Two Strings Intermediate
Python
def uncommon_words(str1, str2):
    words1, words2 = set(str1.split()), set(str2.split())
    return sorted(words1 ^ words2)  # symmetric difference

print(uncommon_words('apple banana mango', 'banana fruits mango'))
# ['apple', 'fruits']
#76 Find Duplicate Characters in a String Intermediate
Python
from collections import Counter

text = "programming"

dupes = [ch for ch, n in Counter(text).items() if n > 1]
print(dupes)  # ['r', 'g', 'm']
#77 Check for Special Characters Intermediate
Python
import re

def has_special(s):
    return bool(re.search(r'[^A-Za-z0-9\s]', s))

print(has_special('Hello World'))   # False
print(has_special('Hello@World!'))  # True
#78 Check Order of Characters in a String Intermediate
Python
from collections import OrderedDict

def check_order(s, pattern):
    d = OrderedDict.fromkeys(s)
    p = 0
    for key in d:
        if key == pattern[p]:
            p += 1
        if p == len(pattern):
            return True
    return False

print(check_order('engineers rock', 'er'))   # True
print(check_order('engineers rock', 'egr'))  # False
#79 Sort Comma-Separated Words Intermediate
Python
line = input("Enter comma-separated words: ")
# e.g. without,hello,bag,world

words = line.split(',')
print(','.join(sorted(words)))
# bag,hello,without,world
#80 Remove Duplicate Words and Sort Intermediate
Python
line = input("Enter words: ")
# e.g. hello world and practice makes perfect and hello world again

unique = sorted(set(line.split()))
print(' '.join(unique))
# again and hello makes perfect practice world
#81 Count Letters and Digits in a Sentence Intermediate
Python
sentence = input("Enter a sentence: ")
# e.g. hello world! 123

letters = sum(ch.isalpha() for ch in sentence)
digits = sum(ch.isdigit() for ch in sentence)

print(f"LETTERS {letters}")  # LETTERS 10
print(f"DIGITS {digits}")    # DIGITS 3
#82 Password Validity Checker Intermediate
Python
import re

def is_valid(pw):
    # 6-12 chars, at least one lowercase, uppercase,
    # digit and special character from [$#@]
    if not 6 <= len(pw) <= 12: return False
    if not re.search(r'[a-z]', pw): return False
    if not re.search(r'[A-Z]', pw): return False
    if not re.search(r'[0-9]', pw): return False
    if not re.search(r'[$#@]', pw): return False
    return True

print(is_valid('ABd1234@1'))  # True
print(is_valid('a F1#'))      # False (too short)
#83 Extract Username and Company from Email Intermediate
Python
import re

email = "john.doe@techforge.com"

m = re.match(r'(?P<user>[\w.]+)@(?P<company>\w+)\.com', email)
print(m.group('user'))     # john.doe
print(m.group('company'))  # techforge

# Without regex
user, domain = email.split('@')
print(user, domain.split('.')[0])
#84 Stutter a Word Intermediate
Python
def stutter(word):
    start = word[:2]
    return f"{start}... {start}... {word}?"

print(stutter('incredible'))
# in... in... incredible?
print(stutter('enthusiastic'))
# en... en... enthusiastic?
#85 Replace Vowels with a Character Intermediate
Python
def replace_vowels(s, ch):
    return ''.join(ch if c.lower() in 'aeiou' else c for c in s)

print(replace_vowels('the aardvark', '#'))
# th# ##rdv#rk
print(replace_vowels('minnie mouse', '?'))
# m?nn?? m??s?
#86 Hamming Distance Between Two Strings Intermediate
Python
def hamming_distance(s1, s2):
    # number of positions where characters differ
    return sum(a != b for a, b in zip(s1, s2))

print(hamming_distance('abcde', 'bcdef'))  # 5
print(hamming_distance('abcde', 'abcde'))  # 0
#87 Reverse a String and Swap Case Intermediate
Python
def reverser(s):
    return s[::-1].swapcase()

print(reverser('Hello World'))  # DLROw OLLEh
print(reverser('ReVeRsE'))      # eSrEvEr
#88 Repeat Each Character Once Intermediate
Python
def double_char(s):
    return ''.join(ch * 2 for ch in s)

print(double_char('String'))  # SSttrriinngg
print(double_char('1234!_ ')) # 11223344!!__
#89 Indices of Capital Letters Intermediate
Python
def capital_indices(s):
    return [i for i, ch in enumerate(s) if ch.isupper()]

print(capital_indices('eDaBiT'))       # [1, 3, 5]
print(capital_indices('EdAbIt'))       # [0, 2, 4]
print(capital_indices('strawberry'))   # []
#90 Alphabetize the Letters in a String Intermediate
Python
def alphabet_soup(s):
    return ''.join(sorted(s))

print(alphabet_soup('hello'))   # ehllo
print(alphabet_soup('edabit'))  # abdeit
#91 Secret Society Name from Initials Intermediate
Python
def society_name(names):
    return ''.join(sorted(name[0] for name in names))

print(society_name(['Adam', 'Sarah', 'Malcolm']))
# AMS
print(society_name(['Harry', 'Newt', 'Luna', 'Cho']))
# CHLN
#92 Check if a Word is an Isogram Intermediate
Python
def is_isogram(word):
    # no repeating letters, case-insensitive
    word = word.lower()
    return len(set(word)) == len(word)

print(is_isogram('Algorism'))   # True
print(is_isogram('PasSword'))   # False
print(is_isogram('Consecutive'))# False
#93 Check if Characters Are in Alphabetical Order Intermediate
Python
def is_in_order(s):
    return s == ''.join(sorted(s))

print(is_in_order('abc'))    # True
print(is_in_order('edabit')) # False
print(is_in_order('123'))    # True
print(is_in_order('xyzz'))   # True
#94 Check if a Number is Symmetrical (Palindrome) Intermediate
Python
def is_symmetrical(num):
    s = str(num)
    return s == s[::-1]

print(is_symmetrical(7227))   # True
print(is_symmetrical(12567))  # False
print(is_symmetrical(44444444)) # True
#95 Product of Numbers in a String Intermediate
Python
def multiply_nums(s):
    product = 1
    for n in s.split(', '):
        product *= int(n)
    return product

print(multiply_nums('2, 3'))        # 6
print(multiply_nums('1, 2, 3, 4'))  # 24
print(multiply_nums('10, -2'))      # -20
#96 Capitalize by ASCII Code Parity Intermediate
Python
def ascii_capitalize(s):
    return ''.join(
        ch.upper() if ord(ch.lower()) % 2 == 0 else ch.lower()
        for ch in s
    )

print(ascii_capitalize('to be or not to be!'))
# To Be oR NoT To Be!
print(ascii_capitalize('THE LITTLE MERMAID'))
# THe LiTTLe meRmaiD
#97 Extract Unique Dictionary Values Intermediate
Python
data = {'a': [1, 2], 'b': [3, 1], 'c': [4, 5], 'd': [2, 5]}

unique = sorted({v for values in data.values() for v in values})
print(unique)  # [1, 2, 3, 4, 5]
#98 Sum of All Items in a Dictionary Intermediate
Python
prices = {'apple': 40, 'banana': 10, 'cherry': 90}

print(sum(prices.values()))  # 140
#99 Merge Two Dictionaries Intermediate
Python
d1 = {'a': 1, 'b': 2}
d2 = {'b': 3, 'c': 4}

# Merge operator (Python 3.9+)
print(d1 | d2)        # {'a': 1, 'b': 3, 'c': 4}

# Unpacking (3.5+)
print({**d1, **d2})   # same

# In-place
d1.update(d2)
print(d1)             # same
#100 Key-Value Pair List to Flat Dictionary Intermediate
Python
pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]

flat = dict(pairs)
print(flat)  # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
#101 Insert at the Beginning of an OrderedDict Intermediate
Python
from collections import OrderedDict

od = OrderedDict([('b', 2), ('c', 3)])

od['a'] = 1
od.move_to_end('a', last=False)  # move to front

print(od)  # OrderedDict([('a', 1), ('b', 2), ('c', 3)])
#102 Sort a Dictionary by Key or Value Intermediate
Python
scores = {'maths': 90, 'english': 75, 'science': 85}

# By key
print(dict(sorted(scores.items())))
# {'english': 75, 'maths': 90, 'science': 85}

# By value (descending)
print(dict(sorted(scores.items(), key=lambda kv: kv[1], reverse=True)))
# {'maths': 90, 'science': 85, 'english': 75}
#103 Sum of Budgets in a List of Dictionaries Intermediate
Python
def get_budgets(people):
    return sum(p['budget'] for p in people)

print(get_budgets([
    {'name': 'John', 'age': 21, 'budget': 23000},
    {'name': 'Steve', 'age': 32, 'budget': 40000},
    {'name': 'Martin', 'age': 16, 'budget': 2700},
]))  # 65700
#104 Dictionary to List of (Key, Value) Tuples Intermediate
Python
d = {'D': 1, 'B': 2, 'C': 3}

print(list(d.items()))
# [('D', 1), ('B', 2), ('C', 3)]

# Lower/upper letter mapping
print({ch: ch.upper() for ch in 'abc'})
# {'a': 'A', 'b': 'B', 'c': 'C'}
#105 Add Two Matrices Intermediate
Python
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]

result = [[A[i][j] + B[i][j] for j in range(len(A[0]))]
          for i in range(len(A))]

print(result)  # [[6, 8], [10, 12]]
#106 Multiply Two Matrices Intermediate
Python
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]

result = [[sum(A[i][k] * B[k][j] for k in range(len(B)))
           for j in range(len(B[0]))]
          for i in range(len(A))]

print(result)  # [[19, 22], [43, 50]]
#107 Transpose a Matrix Intermediate
Python
M = [[1, 2, 3],
     [4, 5, 6]]

transposed = [list(row) for row in zip(*M)]
print(transposed)
# [[1, 4], [2, 5], [3, 6]]
#108 Formula: Q = sqrt(2CD/H) Intermediate
Python
import math

# Q = sqrt(2 * C * D / H) with C=50, H=30
# for comma-separated D values
C, H = 50, 30

values = input("Enter D values: ")  # e.g. 100,150,180
results = [str(round(math.sqrt(2 * C * int(d) / H)))
           for d in values.split(',')]

print(','.join(results))  # 18,22,24
#109 Generate a 2D Array of i*j Intermediate
Python
x, y = 3, 5

grid = [[i * j for j in range(y)] for i in range(x)]
print(grid)
# [[0, 0, 0, 0, 0],
#  [0, 1, 2, 3, 4],
#  [0, 2, 4, 6, 8]]
#110 Radians to Degrees Intermediate
Python
import math

def to_degrees(rad):
    return round(rad * 180 / math.pi, 1)

print(to_degrees(1))     # 57.3
print(to_degrees(20))    # 1145.9
print(math.degrees(1))   # built-in equivalent
#111 Check Curzon Number Intermediate
Python
def is_curzon(num):
    # (2^num + 1) divisible by (2*num + 1)
    return (2 ** num + 1) % (2 * num + 1) == 0

print(is_curzon(5))   # True: 33 % 11 == 0
print(is_curzon(10))  # False
print(is_curzon(14))  # True
#112 Area of a Hexagon Intermediate
Python
import math

def hexagon_area(x):
    # regular hexagon with side length x
    return round(3 * math.sqrt(3) * x ** 2 / 2, 1)

print(hexagon_area(1))  # 2.6
print(hexagon_area(2))  # 10.4
print(hexagon_area(3))  # 23.4
#113 Decimal String to Binary Intermediate
Python
def to_binary(decimal_str):
    return bin(int(decimal_str))[2:]

print(to_binary('10'))   # 1010
print(to_binary('35'))   # 100011
print(to_binary('2'))    # 10
#114 Sum of Numbers Divisible by C in a Range Intermediate
Python
def evenly_divisible(a, b, c):
    return sum(x for x in range(a, b + 1) if x % c == 0)

print(evenly_divisible(1, 10, 20))  # 0
print(evenly_divisible(1, 10, 2))   # 30 (2+4+6+8+10)
print(evenly_divisible(1, 10, 3))   # 18 (3+6+9)
#115 Evaluate an Inequality Expression Intermediate
Python
def correct_signs(expr):
    # expr like '3 < 7 < 11' — eval is safe here only
    # because input is restricted to numbers and < >
    return eval(expr)

print(correct_signs('3 < 7 < 11'))          # True
print(correct_signs('13 > 44 > 33 > 1'))    # False
print(correct_signs('1 < 2 < 6 < 9 > 3'))   # True
#116 Paper Fold Thickness Intermediate
Python
def num_layers(n):
    # 0.5mm doubled n times, answer in metres
    thickness_m = 0.0005 * (2 ** n)
    return f"{thickness_m}m"

print(num_layers(1))   # 0.001m
print(num_layers(4))   # 0.008m
print(num_layers(21))  # 1048.576m
#117 Add Element Index to Itself Intermediate
Python
def add_indexes(lst):
    return [i + x for i, x in enumerate(lst)]

print(add_indexes([0, 0, 0, 0, 0]))  # [0, 1, 2, 3, 4]
print(add_indexes([1, 2, 3, 4, 5]))  # [1, 3, 5, 7, 9]
print(add_indexes([5, 4, 3, 2, 1]))  # [5, 5, 5, 5, 5]
#118 Volume of a Cone Intermediate
Python
import math

def cone_volume(h, r):
    return round(math.pi * r ** 2 * h / 3, 2)

print(cone_volume(3, 2))    # 12.57
print(cone_volume(15, 6))   # 565.49
print(cone_volume(7, 28))   # 5747.02
#119 Nth Triangular Number Intermediate
Python
def triangle(n):
    # dots forming a triangle: 1, 3, 6, 10, 15...
    return n * (n + 1) // 2

print(triangle(1))    # 1
print(triangle(6))    # 21
print(triangle(215))  # 23220
#120 Compound Interest Calculator Intermediate
Python
def compound_interest(principal, years, rate, periods):
    # rate compounded `periods` times per year
    amount = principal * (1 + rate / periods) ** (periods * years)
    return round(amount, 2)

print(compound_interest(10000, 10, 0.06, 12))
# 18193.97  ($10,000 at 6% monthly for 10 years)
#121 List of Numbers Divisible by N in a Range Intermediate
Python
def divisible_by(x, y, n):
    return [i for i in range(x, y + 1) if i % n == 0]

print(divisible_by(1, 10, 3))    # [3, 6, 9]
print(divisible_by(7, 9, 2))     # [8]
print(divisible_by(15, 20, 7))   # []
#122 Square Every Digit of a Number Intermediate
Python
def square_digits(num):
    return int(''.join(str(int(d) ** 2) for d in str(num)))

print(square_digits(9119))  # 811181
print(square_digits(2483))  # 416649
print(square_digits(3212))  # 9414
#123 Mean of All Digits Intermediate
Python
def mean_of_digits(num):
    digits = [int(d) for d in str(num)]
    return sum(digits) / len(digits)

print(mean_of_digits(42))    # 3.0
print(mean_of_digits(12345)) # 3.0
print(mean_of_digits(666))   # 6.0
#124 FizzBuzz-Style List (1 to N) Intermediate
Python
def fizz_buzz_list(n):
    out = []
    for i in range(1, n + 1):
        if i % 15 == 0:  out.append('FizzBuzz')
        elif i % 3 == 0: out.append('Fizz')
        elif i % 5 == 0: out.append('Buzz')
        else:            out.append(i)
    return out

print(fizz_buzz_list(15))
# [1, 2, 'Fizz', 4, 'Buzz', ..., 14, 'FizzBuzz']
#125 Validate a Pythagorean Triplet Intermediate
Python
def is_triplet(a, b, c):
    x, y, z = sorted([a, b, c])
    return x ** 2 + y ** 2 == z ** 2

print(is_triplet(3, 4, 5))    # True
print(is_triplet(13, 5, 12))  # True (order doesn't matter)
print(is_triplet(1, 2, 3))    # False
#126 Count Equal Values Among Three Integers Intermediate
Python
def equal(a, b, c):
    unique = len({a, b, c})
    if unique == 1: return 3   # all equal
    if unique == 2: return 2   # two equal
    return 0                   # none equal

print(equal(3, 4, 3))  # 2
print(equal(1, 1, 1))  # 3
print(equal(3, 4, 5))  # 0
03

Advanced Programs

#10 Merge Sort Advanced
Python
def merge_sort(arr):
    if len(arr) <= 1:
        return arr

    mid = len(arr) // 2
    left = merge_sort(arr[:mid])
    right = merge_sort(arr[mid:])

    return merge(left, right)

def merge(left, right):
    result = []
    i = j = 0

    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1

    result.extend(left[i:])
    result.extend(right[j:])
    return result

arr = [38, 27, 43, 3, 9, 82, 10]
print(merge_sort(arr))  # [3, 9, 10, 27, 38, 43, 82]
#11 Quick Sort Advanced
Python
def quick_sort(arr):
    if len(arr) <= 1:
        return arr

    pivot = arr[len(arr) // 2]
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]

    return quick_sort(left) + middle + quick_sort(right)

arr = [3, 6, 8, 10, 1, 2, 1]
print(quick_sort(arr))  # [1, 1, 2, 3, 6, 8, 10]
#12 Stack Implementation Advanced
Python
class Stack:
    def __init__(self):
        self.items = []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        if not self.is_empty():
            return self.items.pop()
        raise IndexError("Stack is empty")

    def peek(self):
        if not self.is_empty():
            return self.items[-1]
        raise IndexError("Stack is empty")

    def is_empty(self):
        return len(self.items) == 0

    def size(self):
        return len(self.items)

stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.pop())    # 3
print(stack.peek())   # 2
#13 Queue Implementation Advanced
Python
from collections import deque

class Queue:
    def __init__(self):
        self.items = deque()

    def enqueue(self, item):
        self.items.append(item)

    def dequeue(self):
        if not self.is_empty():
            return self.items.popleft()
        raise IndexError("Queue is empty")

    def is_empty(self):
        return len(self.items) == 0

    def size(self):
        return len(self.items)

queue = Queue()
queue.enqueue("A")
queue.enqueue("B")
queue.enqueue("C")
print(queue.dequeue())  # A
print(queue.dequeue())  # B
#14 Bank Account System (OOP) Advanced
Python
class BankAccount:
    def __init__(self, balance=0):
        self.__balance = balance
        self.__history = []

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount
            self.__history.append(f"Deposit: {amount}")

    def withdraw(self, amount):
        if 0 < amount <= self.__balance:
            self.__balance -= amount
            self.__history.append(f"Withdraw: {amount}")

    def get_balance(self):
        return self.__balance

    def show_history(self):
        return self.__history

acc = BankAccount(1000)
acc.deposit(500)
acc.withdraw(200)
print(acc.get_balance())      # 1300
print(acc.show_history())
#127 Fibonacci Using Recursion Advanced
Python
def fib(n):
    if n <= 1:
        return n
    return fib(n - 1) + fib(n - 2)

print([fib(i) for i in range(10)])
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

# Memoized — avoids exponential blowup
from functools import lru_cache

@lru_cache(maxsize=None)
def fib_fast(n):
    return n if n <= 1 else fib_fast(n - 1) + fib_fast(n - 2)

print(fib_fast(50))  # 12586269025, instant
#128 Generator: Numbers Divisible by 7 Advanced
Python
class DivisibleBySeven:
    def __init__(self, n):
        self.n = n

    def generate(self):
        for i in range(0, self.n + 1, 7):
            yield i

gen = DivisibleBySeven(50)
print(list(gen.generate()))
# [0, 7, 14, 21, 28, 35, 42, 49]
#129 Generator: Divisible by 5 and 7 Advanced
Python
def div_by_5_and_7(n):
    for i in range(n + 1):
        if i % 35 == 0:  # divisible by both 5 and 7
            yield i

n = int(input("Enter n: "))  # e.g. 100
print(','.join(str(x) for x in div_by_5_and_7(n)))
# 0,35,70
#130 Generator: Even Numbers Up to N Advanced
Python
def even_numbers(n):
    for i in range(0, n + 1, 2):
        yield i

n = int(input("Enter n: "))  # e.g. 10
print(','.join(str(x) for x in even_numbers(n)))
# 0,2,4,6,8,10
#131 Inheritance: Person, Male and Female Advanced
Python
class Person:
    def get_gender(self):
        return 'Unknown'

class Male(Person):
    def get_gender(self):
        return 'Male'

class Female(Person):
    def get_gender(self):
        return 'Female'

print(Male().get_gender())    # Male
print(Female().get_gender())  # Female
#132 Generate All Sentence Combinations Advanced
Python
from itertools import product

subjects = ['I', 'You']
verbs = ['Play', 'Love']
objects = ['Hockey', 'Football']

for s, v, o in product(subjects, verbs, objects):
    print(f"{s} {v} {o}")
# I Play Hockey ... You Love Football (8 sentences)
#133 Compress and Decompress a String Advanced
Python
import zlib

text = 'hello world!' * 4
data = text.encode()

compressed = zlib.compress(data)
print(len(data), '->', len(compressed))  # 48 -> 24

restored = zlib.decompress(compressed).decode()
print(restored == text)  # True
#134 OOP: Shape and Square with area() Advanced
Python
class Shape:
    def area(self):
        return 0

class Square(Shape):
    def __init__(self, length):
        self.length = length

    def area(self):
        return self.length ** 2

print(Shape().area())    # 0
print(Square(5).area())  # 25
#135 Reverse a Boolean Value Advanced
Python
def reverse_bool(value):
    if isinstance(value, bool):
        return not value
    return 'boolean expected'

print(reverse_bool(True))   # False
print(reverse_bool(False))  # True
print(reverse_bool(0))      # boolean expected
#136 Check if a List Trails Another by One Advanced
Python
def simon_says(lst1, lst2):
    # second list must repeat first list shifted by one
    return lst1[:-1] == lst2[1:]

print(simon_says([1, 2], [5, 1]))          # True
print(simon_says([1, 2, 4], [5, 1, 2]))    # True
print(simon_says([1, 2, 3], [5, 5, 1]))    # False
#137 Circle Class: getArea and getPerimeter Advanced
Python
import math

class Circle:
    def __init__(self, radius):
        self.radius = radius

    def get_area(self):
        return round(math.pi * self.radius ** 2, 2)

    def get_perimeter(self):
        return round(2 * math.pi * self.radius, 2)

c = Circle(4.44)
print(c.get_area())       # 61.93
print(c.get_perimeter())  # 27.9