Interview Questions

1) Write a Python program to print all prime numbers up to n.


def print_primes(n):
    for num in range(2, n + 1):
        if is_prime(num):
            print(num, end=" ")

print_primes(10)  # Output: 2 3 5 7

 

2) Write a Python program to reverse a string.


def reverse_string(s):
    return s[::-1]

print(reverse_string("Hello"))  # Output: "olleH"

 

3) Write a Python program to check if a number is even or odd.


def check_even_odd(n):
    return "Even" if n % 2 == 0 else "Odd"

print(check_even_odd(4))  # Output: Even
print(check_even_odd(7))  # Output: Odd

 

4) Write a Python program to find the factorial of a number.


def factorial(n):
    if n == 0 or n == 1:
        return 1
    return n * factorial(n - 1)

print(factorial(5))  # Output: 120

 

5) Write a Python program to check if a string is a palindrome.


def is_palindrome(s):
    return s == s[::-1]

print(is_palindrome("madam"))  # Output: True
print(is_palindrome("hello"))  # Output: False

 

6) Write a Python program to find the largest of three numbers.


def largest_of_three(a, b, c):
    return max(a, b, c)

print(largest_of_three(3, 7, 5))  # Output: 7

 

7) Write a Python program to sum all the items in a list.


def sum_list(lst):
    return sum(lst)

print(sum_list([1, 2, 3, 4]))  # Output: 10

 

8) Write a Python program to count the number of occurrences of an element in a list.


def count_occurrences(lst, elem):
    return lst.count(elem)

print(count_occurrences([1, 2, 3, 4, 2, 2], 2))  # Output: 3

 

9) Write a Python program to remove duplicates from a list.


def remove_duplicates(lst):
    return list(set(lst))

print(remove_duplicates([1, 2, 2, 3, 4, 4]))  # Output: [1, 2, 3, 4]

 

10) Write a Python program to find the intersection of two lists.


def list_intersection(lst1, lst2):
    return list(set(lst1) & set(lst2))

print(list_intersection([1, 2, 3], [2, 3, 4]))  # Output: [2, 3]

 

11) Write a Python program to check whether a number is prime.


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(7))  # Output: True
print(is_prime(10))  # Output: False

 

12) Write a Python program to calculate the Fibonacci sequence up to n numbers.


def fibonacci(n):
    fib_sequence = []
    a, b = 0, 1
    for _ in range(n):
        fib_sequence.append(a)
        a, b = b, a + b
    return fib_sequence

print(fibonacci(5))  # Output: [0, 1, 1, 2, 3]

 

13) Write a Python program to find the GCD (Greatest Common Divisor) of two numbers.


def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

print(gcd(60, 48))  # Output: 12

 

14) Write a Python program to find the LCM (Least Common Multiple) of two numbers.


def lcm(a, b):
    return abs(a * b) // gcd(a, b)

print(lcm(4, 5))  # Output: 20

 

15) Write a Python program to flatten a nested list.


def flatten_list(lst):
    flat_list = []
    for item in lst:
        if isinstance(item, list):
            flat_list.extend(flatten_list(item))
        else:
            flat_list.append(item)
    return flat_list

print(flatten_list([1, [2, [3, 4], 5], 6]))  # Output: [1, 2, 3, 4, 5, 6]

 

16) Write a Python program to check if a string contains only digits.


def is_digit(s):
    return s.isdigit()

print(is_digit("12345"))  # Output: True
print(is_digit("123a5"))  # Output: False

 

17) Write a Python program to sort a list of tuples based on the second element.


def sort_by_second_element(lst):
    return sorted(lst, key=lambda x: x[1])

print(sort_by_second_element([(1, 3), (2, 1), (4, 2)]))  # Output: [(2, 1), (4, 2), (1, 3)]

 

18) Write a Python program to merge two dictionaries.


def merge_dicts(dict1, dict2):
    dict1.update(dict2)
    return dict1

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
print(merge_dicts(dict1, dict2))  # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

 

19) Write a Python program to generate a random number between 1 and 100.


import random

print(random.randint(1, 100))  # Output: A random number between 1 and 100

 

20) Write a Python program to convert a list of strings to integers.


def convert_to_int(lst):
    return [int(i) for i in lst]

print(convert_to_int(["1", "2", "3"]))  # Output: [1, 2, 3]

 

21) Write a Python program to count the frequency of each character in a string.


from collections import Counter

def char_frequency(s):
    return dict(Counter(s))

print(char_frequency("hello"))  # Output: {'h': 1, 'e': 1, 'l': 2, 'o': 1}

 

22) Write a Python program to remove all vowels from a string.


def remove_vowels(s):
    vowels = "aeiouAEIOU"
    return ''.join([char for char in s if char not in vowels])

print(remove_vowels("hello"))  # Output: "hll"

 

23) Write a Python program to find the second largest number in a list.


def second_largest(lst):
    lst = list(set(lst))  # Remove duplicates
    lst.sort()
    return lst[-2] if len(lst) > 1 else None

print(second_largest([1, 3, 5, 7, 5]))  # Output: 5

 

24) Write a Python program to find the common elements in two lists.


def common_elements(lst1, lst2):
    return list(set(lst1) & set(lst2))

print(common_elements([1, 2, 3], [2, 3, 4]))  # Output: [2, 3]

 

25) Write a Python program to find the longest string in a list.


def longest_string(lst):
    return max(lst, key=len)

print(longest_string(["apple", "banana", "cherry"]))  # Output: "banana"

 

26) Write a Python program to reverse the words in a sentence.


def reverse_words(sentence):
    return ' '.join(sentence.split()[::-1])

print(reverse_words("Hello World"))  # Output: "World Hello"

 

27) Write a Python program to check if a string is a valid email address.


import re

def is_valid_email(email):
    pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
    return re.match(pattern, email) is not None

print(is_valid_email("test@example.com"))  # Output: True
print(is_valid_email("invalid-email"))  # Output: False

 

28) Write a Python program to find the sum of all numbers divisible by 3 and 5 below 1000.


def sum_divisible_by_3_and_5():
    return sum(x for x in range(1000) if x % 3 == 0 or x % 5 == 0)

print(sum_divisible_by_3_and_5())  # Output: 233168

 

29) Write a Python program to print a multiplication table of a given number.


def multiplication_table(n):
    for i in range(1, 11):
        print(f"{n} * {i} = {n * i}")

multiplication_table(5)
# Output:
# 5 * 1 = 5
# 5 * 2 = 10
# ...

 

30) Write a Python program to find the average of a list of numbers.


def average(lst):
    return sum(lst) / len(lst)

print(average([1, 2, 3, 4]))  # Output: 2.5