Practice Drills

Python Coding Interview Kit

73 Challenging Coding Problems | Compiled & Translated to Python 3

Syntax Modernization Note: All code snippets have been updated from Python 2 to Python 3. Obsolete constructs like raw_input() have been mapped to input(), print val changed to print(val), unicode() to native string operations, and lazy iterators like map() and filter() have been explicitly cast using list() where required.
Level 1 (Beginner) Drill 1

Find Numbers Divisible by 7 but Not a Multiple of 5

Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line.

Hints: Consider using the range(begin, end) method.
# Python 3 Solution
numbers = []
for i in range(2000, 3201):
    if (i % 7 == 0) and (i % 5 != 0):
        numbers.append(str(i))

print(",".join(numbers))
Level 1 (Beginner) Drill 2

Factorial Calculator

Write a program which can compute the factorial of a given number. The results should be printed in a comma-separated sequence on a single line. (e.g. Input: 8 -> Output: 40320).

# Python 3 Solution
def fact(x):
    if x == 0:
        return 1
    return x * fact(x - 1)

try:
    user_input = int(input("Enter number: "))
    print(fact(user_input))
except ValueError:
    print("Please enter a valid integer.")
Level 1 (Beginner) Drill 3

Generate Square Value Dictionary

With a given integral number n, write a program to generate a dictionary that contains (i, i*i) such that is an integral number between 1 and n (both included). and then the program should print the dictionary. (e.g. Input: 8 -> Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}).

# Python 3 Solution
n = int(input("Enter range: "))
squares_dict = {i: i * i for i in range(1, n + 1)}
print(squares_dict)
Level 1 (Beginner) Drill 4

Unpacking Comma-Separated Input to List and Tuple

Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number. (e.g. Input: 34,67,55,33,12,98 -> Output: ['34', '67', '55', '33', '12', '98'] and ('34', '67', '55', '33', '12', '98')).

# Python 3 Solution
raw_values = input("Enter comma separated numbers: ")
numbers_list = raw_values.split(",")
numbers_tuple = tuple(numbers_list)

print(numbers_list)
print(numbers_tuple)
Level 1 (Beginner) Drill 5

Class with getString and printString Methods

Define a class which has at least two methods: getString (to get a string from console input) and printString (to print the string in upper case).

# Python 3 Solution
class StringHandler:
    def __init__(self):
        self.user_str = ""

    def get_string(self):
        self.user_str = input("Enter string value: ")

    def print_string(self):
        print(self.user_str.upper())

# Testing
handler = StringHandler()
# handler.get_string()
# handler.print_string()
Level 2 (Intermediate) Drill 6

Calculate Value from Dynamic Formula

Write a program that calculates and prints the value according to the given formula: $Q = \sqrt{(2 * C * D) / H}$. Fixed values are C=50 and H=30. D is a dynamic variable input in a comma-separated sequence. (e.g. Input: 100,150,180 -> Output: 18,22,24).

# Python 3 Solution
import math

C = 50
H = 30
results = []
raw_inputs = input("Enter values for D: ").split(",")

for d in raw_inputs:
    q_val = math.sqrt((2 * C * float(d)) / H)
    results.append(str(round(q_val)))

print(",".join(results))
Level 2 (Intermediate) Drill 7

Generate 2-Dimensional Matrix (i * j)

Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th row and j-th column of the array should be i*j. (e.g. Input: 3,5 -> Output: [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]).

# Python 3 Solution
dimensions = [int(x) for x in input("Enter X,Y: ").split(",")]
rows, cols = dimensions[0], dimensions[1]

matrix = [[row * col for col in range(cols)] for row in range(rows)]
print(matrix)
Level 2 (Intermediate) Drill 8

Sorting Words Alphabetically

Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically. (e.g. Input: without,hello,bag,world -> Output: bag,hello,without,world).

# Python 3 Solution
words = [w for w in input("Enter words: ").split(",")]
words.sort()
print(",".join(words))
Level 2 (Intermediate) Drill 9

Capitalize Continuous Lines of Console Input

Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized.

# Python 3 Solution
sentences = []
print("Enter sentences (press Enter on empty line to finish):")
while True:
    line = input()
    if line:
        sentences.append(line.upper())
    else:
        break

for item in sentences:
    print(item)
Level 2 (Intermediate) Drill 10

Deduplicate and Alphanumerically Sort Sentence Words

Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically. (e.g. Input: hello world and practice makes perfect and hello world again -> Output: again and hello makes perfect practice world).

# Python 3 Solution
raw_words = input("Enter sentence: ").split(" ")
unique_sorted_words = sorted(list(set(raw_words)))
print(" ".join(unique_sorted_words))
Level 2 (Intermediate) Drill 11

Filter Binary Inputs Divisible by 5

Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. (e.g. Input: 0100,0011,1010,1001 -> Output: 1010).

# Python 3 Solution
divisible_binaries = []
raw_binaries = input("Enter 4-digit binaries: ").split(",")

for binary_str in raw_binaries:
    if int(binary_str, 2) % 5 == 0:
        divisible_binaries.append(binary_str)

print(",".join(divisible_binaries))
Level 2 (Intermediate) Drill 12

Find Numbers with All-Even Digits

Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number. The numbers obtained should be printed in a comma-separated sequence on a single line.

# Python 3 Solution
even_digit_numbers = []
for i in range(1000, 3001):
    digits_str = str(i)
    if all(int(char) % 2 == 0 for char in digits_str):
        even_digit_numbers.append(digits_str)

print(",".join(even_digit_numbers))
Level 2 (Intermediate) Drill 13

Count Letters and Digits inside Sentence

Write a program that accepts a sentence and calculate the number of letters and digits. (e.g. Input: hello world! 123 -> Output: LETTERS 10, DIGITS 3).

# Python 3 Solution
text = input("Enter sentence: ")
counts = {"DIGITS": 0, "LETTERS": 0}

for char in text:
    if char.isdigit():
        counts["DIGITS"] += 1
    elif char.isalpha():
        counts["LETTERS"] += 1

print(f"LETTERS {counts['LETTERS']}")
print(f"DIGITS {counts['DIGITS']}")
Level 2 (Intermediate) Drill 14

Count Uppercase and Lowercase Letters

Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters. (e.g. Input: Hello world! -> Output: UPPER CASE 1, LOWER CASE 9).

# Python 3 Solution
sentence = input("Enter sentence: ")
cases = {"UPPER": 0, "LOWER": 0}

for char in sentence:
    if char.isupper():
        cases["UPPER"] += 1
    elif char.islower():
        cases["LOWER"] += 1

print(f"UPPER CASE {cases['UPPER']}")
print(f"LOWER CASE {cases['LOWER']}")
Level 2 (Intermediate) Drill 15

Compute String Sequence Addition (a + aa + aaa + aaaa)

Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a. (e.g. Input: 9 -> Output: 11106).

# Python 3 Solution
val_char = input("Enter digit a: ")

n1 = int(f"{val_char}")
n2 = int(f"{val_char * 2}")
n3 = int(f"{val_char * 3}")
n4 = int(f"{val_char * 4}")

print(n1 + n2 + n3 + n4)
Level 2 (Intermediate) Drill 16

Square Each Odd Number from Comma-Separated Input

Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers. (e.g. Input: 1,2,3,4,5,6,7,8,9 -> Output: 1,9,25,49,81).

# Python 3 Solution
raw_values = input("Enter numbers: ")
squared_odds = [str(int(x)**2) for x in raw_values.split(",") if int(x) % 2 != 0]
print(",".join(squared_odds))
Level 2 (Intermediate) Drill 17

Bank Account Log Balance Calculator

Write a program that computes the net amount of a bank account based a transaction log from console input. D means deposit while W means withdrawal. (e.g. Input: D 300, D 300, W 200, D 100 -> Output: 500).

# Python 3 Solution
net_amount = 0
print("Enter log row by row (press Enter on empty row to submit):")

while True:
    log_row = input()
    if not log_row:
        break
    parts = log_row.split(" ")
    action = parts[0].upper()
    amount = int(parts[1])
    
    if action == "D":
        net_amount += amount
    elif action == "W":
        net_amount -= amount

print(net_amount)
Level 3 (Advanced) Drill 18

Regex Password Validity Assertion Gate

Check the validity of dynamic passwords. Criteria: At least 1 lowercase [a-z], 1 digit [0-9], 1 uppercase [A-Z], 1 special char [$#@], Min len: 6, Max len: 12. Input a sequence of comma-separated passwords; output matches separated by commas.

# Python 3 Solution
import re

valid_passwords = []
passwords = input("Enter passwords to validate: ").split(",")

for p in passwords:
    if len(p) < 6 or len(p) > 12:
        continue
    if not re.search("[a-z]", p):
        continue
    if not re.search("[0-9]", p):
        continue
    if not re.search("[A-Z]", p):
        continue
    if not re.search("[$#@]", p):
        continue
    if re.search(r"\s", p):
        continue
    valid_passwords.append(p)

print(",".join(valid_passwords))
Level 3 (Advanced) Drill 19

Sorting Multi-Key Tuples (Name, Age, Score)

You are required to write a program to sort the (name, age, height) tuples by ascending order where name is string, age and height are numbers. Priority order is Name > Age > Score.

# Python 3 Solution
from operator import itemgetter

records = []
print("Enter tuples (Name,Age,Score) line by line (empty line to complete):")
while True:
    line_input = input()
    if not line_input:
        break
    parts = line_input.split(",")
    # Keep age/score as integers/floats for accurate relative numeric sorting
    records.append((parts[0], int(parts[1]), int(parts[2])))

sorted_records = sorted(records, key=itemgetter(0, 1, 2))
print(sorted_records)
Level 3 (Advanced) Drill 20

Custom Generator Divisible by 7

Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n.

# Python 3 Solution
class DivisibleGenerator:
    def __init__(self, limit):
        self.limit = limit

    def get_divisible_by_seven(self):
        for num in range(self.limit + 1):
            if num % 7 == 0:
                yield num

# Test Execution
generator_inst = DivisibleGenerator(50)
for val in generator_inst.get_divisible_by_seven():
    print(val)
Level 3 (Advanced) Drill 21

Robot Navigation Grid Distance Calculator

Compute the Euclidean distance of a robot starting from original point (0,0). Valid inputs: UP steps, DOWN steps, LEFT steps, RIGHT steps. If distance is float, print nearest integer.

# Python 3 Solution
import math

position = [0, 0]
print("Enter robot movements (e.g. UP 5) line by line (empty line to process):")

while True:
    move_log = input()
    if not move_log:
        break
    parts = move_log.split(" ")
    direction = parts[0].upper()
    steps = int(parts[1])
    
    if direction == "UP":
        position[1] += steps
    elif direction == "DOWN":
        position[1] -= steps
    elif direction == "LEFT":
        position[0] -= steps
    elif direction == "RIGHT":
        position[0] += steps

distance = math.sqrt(position[0]**2 + position[1]**2)
print(round(distance))
Level 3 (Advanced) Drill 22

Word Frequency Map Alphanumeric Sorter

Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically.

# Python 3 Solution
freq_map = {}
line_input = input("Enter sentence: ")

for word in line_input.split():
    freq_map[word] = freq_map.get(word, 0) + 1

# Sorted alphanumeric keys
sorted_keys = sorted(freq_map.keys())

for key in sorted_keys:
    print(f"{key}:{freq_map[key]}")
Level 1 (Beginner) Drill 23

Compute Square Value

Write a method which can calculate square value of number using double asterisks.

# Python 3 Solution
def square(num):
    return num ** 2

print(square(5))
Level 1 (Beginner) Drill 24

Dynamic Document Reader (__doc__)

Write a program to print Python built-in functions documentation (e.g. abs(), int()) and implement custom documentation reading interfaces.

# Python 3 Solution
print(abs.__doc__)
print(int.__doc__)

def calculate_volume(r):
    """Computes total sphere volume from static radius."""
    import math
    return (4/3) * math.pi * (r ** 3)

print(calculate_volume.__doc__)
Level 1 (Beginner) Drill 25

Static/Class Parameter vs Instance Scope

Define a class, which have a class parameter and have a same instance parameter.

# Python 3 Solution
class Person:
    # Class-level parameter (shared fallback)
    name = "Default Person"
    
    def __init__(self, name=None):
        if name is not None:
            # Instance-level parameter
            self.name = name

jeff = Person("Jeffrey")
print(f"Class attribute: {Person.name} | Instance attribute: {jeff.name}")
Level 1 (Beginner) Drill 26

Sum of Two Integers

Define a function with two numbers as arguments. Compute the sum and return it.

# Python 3 Solution
def get_sum(n1, n2):
    return n1 + n2

print(get_sum(12, 18))
Level 1 (Beginner) Drill 27

Convert Integer to String representation

Define a function that can convert an integer into a string and print it in console.

# Python 3 Solution
def print_as_string(num):
    print(str(num))

print_as_string(450)
Level 1 (Beginner) Drill 28

Calculate sum of string representation numbers

Define a function that can receive two integral numbers in string form and compute their sum and then print it in console.

# Python 3 Solution
def calculate_string_sum(s1, s2):
    print(int(s1) + int(s2))

calculate_string_sum("10", "20")
Level 1 (Beginner) Drill 29

Concatenate Two Strings

Define a function that can accept two strings as input and concatenate them and then print it in console.

# Python 3 Solution
def concat_strings(s1, s2):
    print(s1 + s2)

concat_strings("Data", "Engineering")
Level 1 (Beginner) Drill 30

Print String with Maximum Length

Define a function that can accept two strings as input and print the string with maximum length. If they are equal, print them line-by-line.

# Python 3 Solution
def print_longest_string(s1, s2):
    l1, l2 = len(s1), len(s2)
    if l1 > l2:
        print(s1)
    elif l2 > l1:
        print(s2)
    else:
        print(s1)
        print(s2)

print_longest_string("Python", "Rust")
Level 1 (Beginner) Drill 31

Modulo Even/Odd checker

Define a function that can accept an integer number as input and print if it is even or odd.

# Python 3 Solution
def verify_even_odd(number):
    if number % 2 == 0:
        print("It is an even number")
    else:
        print("It is an odd number")

verify_even_odd(15)
Level 1 (Beginner) Drill 32

Dictionary Squares Map (1 to 3)

Define a function which can print a dictionary where the keys are numbers between 1 and 3 (both included) and the values are square of keys.

# Python 3 Solution
def create_squares_1_to_3():
    squares_map = {i: i ** 2 for i in range(1, 4)}
    print(squares_map)

create_squares_1_to_3()
Level 1 (Beginner) Drill 33

Dictionary Squares Map (1 to 20)

Define a function which can print a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys.

# Python 3 Solution
def create_squares_1_to_20():
    squares_map = {i: i ** 2 for i in range(1, 21)}
    print(squares_map)

create_squares_1_to_20()
Level 1 (Beginner) Drill 34

Print Dictionary Values Only (1 to 20)

Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should print the values only.

# Python 3 Solution
def print_dict_values():
    d = {i: i**2 for i in range(1, 21)}
    for val in d.values():
        print(val)

print_dict_values()
Level 1 (Beginner) Drill 35

Print Dictionary Keys Only (1 to 20)

Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should print the keys only.

# Python 3 Solution
def print_dict_keys():
    d = {i: i**2 for i in range(1, 21)}
    for key in d.keys():
        print(key)

print_dict_keys()
Level 1 (Beginner) Drill 36

Generate and Print Squares List

Define a function which can generate and print a list where the values are square of numbers between 1 and 20 (both included).

# Python 3 Solution
def generate_squares_list():
    squares_list = [i**2 for i in range(1, 21)]
    print(squares_list)

generate_squares_list()
Level 1 (Beginner) Drill 37

Print First 5 Elements in List

Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the first 5 elements in the list.

# Python 3 Solution
def print_first_five():
    squares_list = [i**2 for i in range(1, 21)]
    print(squares_list[:5])

print_first_five()
Level 1 (Beginner) Drill 38

Print Last 5 Elements in List

Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the last 5 elements in the list.

# Python 3 Solution
def print_last_five():
    squares_list = [i**2 for i in range(1, 21)]
    print(squares_list[-5:])

print_last_five()
Level 1 (Beginner) Drill 39

Print List Except First 5 Elements

Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print all values except the first 5 elements.

# Python 3 Solution
def print_excluding_first_five():
    squares_list = [i**2 for i in range(1, 21)]
    print(squares_list[5:])

print_excluding_first_five()
Level 1 (Beginner) Drill 40

Generate and Print Squares Tuple

Define a function which can generate and print a tuple where the value are square of numbers between 1 and 20 (both included).

# Python 3 Solution
def print_squares_tuple():
    squares_tuple = tuple(i**2 for i in range(1, 21))
    print(squares_tuple)

print_squares_tuple()
Level 1 (Beginner) Drill 41

Tuple slicing (First half vs Second half)

With a given tuple (1,2,3,4,5,6,7,8,9,10), write a program to print the first half values in one line and the last half values in one line.

# Python 3 Solution
original_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
halfway_index = len(original_tuple) // 2

print(original_tuple[:halfway_index])
print(original_tuple[halfway_index:])
Level 1 (Beginner) Drill 42

Generate Even Values Tuple from Tuple

Write a program to generate and print another tuple whose values are even numbers in the given tuple (1,2,3,4,5,6,7,8,9,10).

# Python 3 Solution
orig_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
even_tuple = tuple(x for x in orig_tuple if x % 2 == 0)
print(even_tuple)
Level 1 (Beginner) Drill 43

Conditional Verification String Matcher

Write a program which accepts a string as input to print "Yes" if the string is "yes" or "YES" or "Yes", otherwise print "No".

# Python 3 Solution
user_str = input("Enter confirmation value: ").strip()

if user_str in ("yes", "YES", "Yes"):
    print("Yes")
else:
    print("No")
Level 1 (Beginner) Drill 44

Filtering even numbers using filter()

Write a program which can filter even numbers in a list by using filter function. The list is: [1,2,3,4,5,6,7,8,9,10].

# Python 3 Solution
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_nums = list(filter(lambda x: x % 2 == 0, nums))
print(even_nums)
Level 1 (Beginner) Drill 45

Transforming array values using map()

Write a program which can map() to make a list whose elements are square of elements in [1,2,3,4,5,6,7,8,9,10].

# Python 3 Solution
values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squared_values = list(map(lambda x: x**2, values))
print(squared_values)
Level 1 (Beginner) Drill 46

Chaining map() and filter()

Write a program which can map() and filter() to make a list whose elements are square of even number in [1,2,3,4,5,6,7,8,9,10].

# Python 3 Solution
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
transformed = list(map(lambda x: x**2, filter(lambda x: x % 2 == 0, nums)))
print(transformed)
Level 1 (Beginner) Drill 47

Filter Even Range Outputs

Write a program which can filter() to make a list whose elements are even number between 1 and 20 (both included).

# Python 3 Solution
even_numbers = list(filter(lambda x: x % 2 == 0, range(1, 21)))
print(even_numbers)
Level 1 (Beginner) Drill 48

Square generation using map() over ranges

Write a program which can map() to make a list whose elements are square of numbers between 1 and 20 (both included).

# Python 3 Solution
squares = list(map(lambda x: x**2, range(1, 21)))
print(squares)
Level 1 (Beginner) Drill 49

Class definition with Static Methods

Define a class named American which has a static method called printNationality.

# Python 3 Solution
class American:
    @staticmethod
    def print_nationality():
        print("America")

# Execution
American.print_nationality()
Level 1 (Beginner) Drill 50

Class Inheritance Definitions

Define a class named American and its subclass NewYorker.

# Python 3 Solution
class American:
    pass

class NewYorker(American):
    pass

ny = NewYorker()
print(isinstance(ny, American))  # True
Level 1 (Beginner) Drill 51

Circle Class Area Calculation

Define a class named Circle which can be constructed by a radius. The Circle class has a method which can compute the area.

# Python 3 Solution
import math

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

    def calculate_area(self):
        return (self.radius ** 2) * math.pi

c = Circle(4)
print(round(c.calculate_area(), 2))
Level 1 (Beginner) Drill 52

Rectangle Class Area Calculation

Define a class named Rectangle which can be constructed by a length and width. The Rectangle class has a method which can compute the area.

# Python 3 Solution
class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def calculate_area(self):
        return self.length * self.width

rect = Rectangle(10, 5)
print(rect.calculate_area())
Level 1 (Beginner) Drill 53

Shape Base Class Method Overriding

Define a class named Shape and its subclass Square. The Square class has an init function which takes a length as argument. Both classes have a area function where Shape's area is 0 by default.

# Python 3 Solution
class Shape:
    def area(self):
        return 0

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

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

sq = Square(5)
print(sq.area())
Level 1 (Beginner) Drill 54

Raising Custom Exception Error

Please raise a RuntimeError exception with custom explanation text.

# Python 3 Solution
# raise RuntimeError('Incomplete initialization config')
Level 1 (Beginner) Drill 55

Divide by Zero Exception Handler Gate

Write a function to compute 5/0 and use try/except to catch the exceptions.

# Python 3 Solution
def divide_by_zero():
    return 5 / 0

try:
    divide_by_zero()
except ZeroDivisionError:
    print("Error: Handled mathematical division by zero.")
except Exception as e:
    print(f"Caught generic error: {e}")
finally:
    print("Cleanup actions completed inside finally block.")
Level 1 (Beginner) Drill 56

Custom Exception Definitions

Define a custom exception class which takes a string message as attribute.

# Python 3 Solution
class PayloadValidationError(Exception):
    """Custom schema failure exceptions

    Attributes:
        msg -- Error details
    """
    def __init__(self, msg):
        self.msg = msg

# try:
#     raise PayloadValidationError("Missing mandatory field: 'id'")
# except PayloadValidationError as err:
#     print(err.msg)
Level 1 (Beginner) Drill 57

Regex Match Username from Email Payload

Assuming email addresses are formatted as "username@companyname.com", extract the username containing alphanumeric characters only.

# Python 3 Solution
import re

email_address = input("Enter email: ")
pattern = r"^(\w+)@(\w+)\.com$"
matcher = re.match(pattern, email_address)

if matcher:
    print(f"Username: {matcher.group(1)}")
else:
    print("No valid match found.")
Level 1 (Beginner) Drill 58

Regex Match Company Name from Email Payload

Assuming email addresses are formatted as "username@companyname.com", extract the company name.

# Python 3 Solution
import re

email_address = input("Enter email: ")
pattern = r"^(\w+)@(\w+)\.com$"
matcher = re.match(pattern, email_address)

if matcher:
    print(f"Company: {matcher.group(2)}")
Level 1 (Beginner) Drill 59

Regex findall Numbers Parsing

Write a program which accepts a sequence of words separated by whitespace as input to print the words composed of digits only. (e.g. Input: "2 cats and 3 dogs" -> Output: ['2', '3']).

# Python 3 Solution
import re

text = input("Enter values containing digits: ")
digits_list = re.findall(r"\d+", text)
print(digits_list)
Level 1 (Beginner) Drill 60

Dynamic Sum Arithmetic Sequences

Write a program to compute $1/2+2/3+3/4+...+n/n+1$ with a given n input by console (n>0). (e.g. Input: 5 -> Output: 3.55).

# Python 3 Solution
n = int(input("Enter sequence length n: "))
sequence_sum = sum(i / (i + 1) for i in range(1, n + 1))
print(round(sequence_sum, 2))
Level 1 (Beginner) Drill 61

Recursive Sequence Addition ($f(n) = f(n-1) + 100$)

Compute the recursive sequence: $f(n)=f(n-1)+100$ when n>0 and $f(0)=0$ (or 1 depend on default initialization definitions).

# Python 3 Solution
def f(n):
    if n == 0:
        return 0
    return f(n - 1) + 100

print(f(5))
Level 1 (Beginner) Drill 62

Fibonacci Recursive Term Calculator

Compute Fibonacci values $f(n)$ where $f(n)=0$ if $n=0$, $f(n)=1$ if $n=1$, and $f(n)=f(n-1)+f(n-2)$ if $n>1$.

# Python 3 Solution
def fib(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    return fib(n - 1) + fib(n - 2)

print(fib(7))  # Output: 13
Level 1 (Beginner) Drill 63

Fibonacci Series Array Extractor

Write a program using list comprehension to print the Fibonacci Sequence in comma separated form with a given n input by console. (e.g. Input: 7 -> Output: 0,1,1,2,3,5,8,13).

# Python 3 Solution
def fib(n):
    if n == 0: return 0
    if n == 1: return 1
    return fib(n - 1) + fib(n - 2)

n = int(input("Enter range: "))
fib_sequence = [str(fib(x)) for x in range(n + 1)]
print(",".join(fib_sequence))
Level 1 (Beginner) Drill 64

Generator Yielding Even Numbers

Please write a program using generator to print the even numbers between 0 and n in comma separated form while n is input by console.

# Python 3 Solution
def even_generator(limit):
    for i in range(limit + 1):
        if i % 2 == 0:
            yield i

n_limit = int(input("Enter generator boundary: "))
even_vals = [str(val) for val in even_generator(n_limit)]
print(",".join(even_vals))
Level 1 (Beginner) Drill 65

Generator Yielding Divisible Values (5 and 7)

Please write a program using generator to print the numbers which can be divisible by 5 and 7 between 0 and n in comma separated form while n is input by console.

# Python 3 Solution
def divisible_by_5_and_7(limit):
    for i in range(limit + 1):
        if i % 5 == 0 and i % 7 == 0:
            yield i

limit_num = int(input("Enter target range: "))
outputs = [str(x) for x in divisible_by_5_and_7(limit_num)]
print(",".join(outputs))
Level 1 (Beginner) Drill 66

Validating Range Assertion expressions

Write assert statements to verify that every number in the list [2,4,6,8] is even.

# Python 3 Solution
even_numbers_list = [2, 4, 6, 8]
for num in even_numbers_list:
    assert num % 2 == 0, f"Validation failure: {num} is not even."
Level 1 (Beginner) Drill 67

Evaluating Dynamic Mathematic Expressions

Write a program which accepts basic mathematic expression from console and print the evaluation result. (e.g. Input: "35+3" -> Output: 38).

# Python 3 Solution
expression_string = input("Enter expression: ")
print(eval(expression_string))
Level 2 (Intermediate) Drill 68

Binary Search Algorithm Logic

Write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list.

# Python 3 Solution
def binary_search(sorted_list, target):
    low = 0
    high = len(sorted_list) - 1
    
    while low <= high:
        mid = (low + high) // 2
        if sorted_list[mid] == target:
            return mid
        elif sorted_list[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1

# Testing
search_space = [2, 5, 7, 9, 11, 17, 222]
print(binary_search(search_space, 11))   # Output: 4
Level 1 (Beginner) Drill 69

Random Float boundaries mapping

Please generate a random float where the value is between 10 and 100.

# Python 3 Solution
import random
# Outputs a random float [10, 100]
print(random.uniform(10, 100))
Level 1 (Beginner) Drill 70

Random Sample Choices Inside Lists

Please write a program to generate a list with 5 random numbers between 100 and 200 inclusive.

# Python 3 Solution
import random
# Pulls 5 unique integers in target range
print(random.sample(range(100, 201), 5))
Level 2 (Intermediate) Drill 71

String Compression using zlib

Write a program to compress and decompress the string "hello world!hello world!hello world!hello world!".

# Python 3 Solution
import zlib

original_bytes = b"hello world!hello world!hello world!hello world!"
compressed_data = zlib.compress(original_bytes)
decompressed_data = zlib.decompress(compressed_data)

print(f"Compressed size: {len(compressed_data)}")
print(f"Decompressed: {decompressed_data.decode('utf-8')}")
Level 2 (Intermediate) Drill 72

Generate Dynamic Sentences via Combinations

Write a program to generate all sentences where subject is in ["I", "You"] and verb is in ["Play", "Love"] and the object is in ["Hockey","Football"].

# Python 3 Solution
import itertools

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

for s, v, o in itertools.product(subjects, verbs, objects):
    print(f"{s} {v} {o}.")
Level 3 (Advanced) Drill 73

Chinese Puzzle Matrix Solver (Chickens and Rabbits)

Solve ancient math puzzle: 35 heads and 94 legs among chickens and rabbits. Calculate count of each animal.

# Python 3 Solution
def solve_puzzle(heads, legs):
    # i represents chickens, j represents rabbits
    for i in range(heads + 1):
        j = heads - i
        if (2 * i) + (4 * j) == legs:
            return i, j
    return None, None

chickens, rabbits = solve_puzzle(35, 94)
print(f"Chickens: {chickens} | Rabbits: {rabbits}")