Al Akhawayn University - Spring 2025 School of Science and Engineering
Data structure - Python Review Exercises
Below is a reorganized set of exercises divided into three categories (Introductory, Medium,
and Difficult). Each exercise includes a brief description and an example (where relevant).
Introductory Exercises
1. Calculate Average of Numbers
Description: Ask the user how many numbers they want to enter, then read each
number and calculate the average.
Example:
• Input:
– count = 5
– Numbers: 10, 20, 30, 40, 50
• Output: The average is 30.0.
2. Quadratic Equation Roots
Description: Given coefficients a, b, and c of the quadratic equation ax2 + bx + c = 0,
compute the roots using the quadratic formula. Check whether the roots are real or
complex.
Example:
• Input: a = 1, b = −3, c = 2
• Output: Real roots: x1 = 2, x2 = 1.
3. Generate Pairs from Two Tuples
Description: Take two tuples, e.g. (1, 2) and (3, 4), and generate all possible pairs
between them.
Example:
• Input: t1 = (1, 2), t2 = (3, 4)
• Output: [(1, 3), (1, 4), (2, 3), (2, 4)]
4. Floyd’s Triangle
Description: Print Floyd’s triangle (or pyramid) for a given number of rows.
Example (for 5 rows):
1
Al Akhawayn University - Spring 2025 School of Science and Engineering
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
5. Check Perfect Number
Description: A perfect number is one that equals the sum of its proper divisors. Check
if a user-input number is perfect.
Example:
• 6 is perfect because 6 = 1 + 2 + 3.
• 28 is perfect because 28 = 1 + 2 + 4 + 7 + 14.
6. Max Product Pair in a Tuple
Description: Given a tuple of integers, find two numbers whose product is the largest.
Example:
• Input: (1, 10, 3, 7, −5, 6)
• Output: (10, 7) (product = 70).
7. Rotate a List (Simple Version)
Description: Rotate the elements of a list to the right by a given number of steps.
Create a new rotated list (not necessarily in-place).
Example:
• Input list: [1, 2, 3, 4, 5], steps: 2
• Output: [4, 5, 1, 2, 3]
8. Remove Duplicates from a List
Description: Remove duplicate elements from a list while preserving the original order.
Example:
• Input: [1, 2, 2, 3, 4, 4, 5]
• Output: [1, 2, 3, 4, 5]
9. Count Vowels in a String
Description: Prompt the user for a string and count how many vowels (a, e, i, o, u) it
contains.
Hints:
2
Al Akhawayn University - Spring 2025 School of Science and Engineering
• Convert the string to lowercase for ease of checking.
• Use a simple loop or a comprehension:
10. Dictionary Merge
Description: Write a function that takes two dictionaries and merges them. If a key
exists in both, sum their values (assume they are numeric).
Example:
• d1 = {’apple’: 10, ’banana’: 5}
• d2 = {’banana’: 3, ’orange’: 7}
• Output: {’apple’: 10, ’banana’: 8, ’orange’: 7}
11. Dictionary Key with Maximum Value
Description: Given a dictionary of {key : number} pairs, find the key that has the
maximum value.
Example:
• scores = {"Aya": 10, "Taha": 25, "Karim": 20}
• Output: Taha (since 25 is the max)
12. Set Operations
Description: Prompt the user for two lists of numbers, convert them into sets, then
display their union, intersection, and difference.
Example:
• Set1 = {1, 2, 3, 4}
• Set2 = {3, 4, 5, 6}
• Output:
– Union: {1, 2, 3, 4, 5, 6}
– Intersection: {3, 4}
– Difference (Set1 - Set2): {1, 2}
13. String Reversal Function
Description: Write a function reverse_string(text) that returns the reversed ver-
sion of text.
Example:
• reverse_string("hello") -> "olleh"
3
Al Akhawayn University - Spring 2025 School of Science and Engineering
• reverse_string("Python") -> "nohtyP"
Medium Exercises
1. Check Magic Square
Description: A 2D square matrix is “magic” if the sums of all rows, columns, and the
two main diagonals are the same. Write a function to check if a given 2D list is a magic
square.
Example:
• Input:
[
[8, 1, 6],
[3, 5, 7],
[4, 9, 2]
]
• Each row, column, diagonal sums to 15 → It is a magic square.
2. Sudoku Validator (9x9)
Description: Given a 9x9 Sudoku board stored as a 2D list, verify if the board is
valid. Each row, column, and each 3x3 sub-grid must contain the numbers 1 through
9 exactly once (without repetition).
Example:
• Input: a partially completed or full Sudoku grid.
• Output: True if valid so far, otherwise False.
3. Longest Word in a String
Description: Prompt the user for a sentence, then find and return the longest word.
Hint: Use split() to separate words and track the longest by length.
4. Update Inventory with Sets and Dictionaries
Description: You have a dictionary representing an inventory (name → quantity).
Then you receive a set of new items (no specified quantity). Update the dictionary so
that each item in the set is incremented by 1 if it exists, or added with quantity 1 if it
doesn’t.
Example:
4
Al Akhawayn University - Spring 2025 School of Science and Engineering
• inventory = {"pen": 10, "pencil": 5}
• shipment = {"pencil", "eraser", "paper"}
• Output: {"pen": 10, "pencil": 6, "eraser": 1, "paper": 1}
5. String Compression
Description: Given a string like "aaabbc", compress it to "a3b2c1".
Hint:
• Iterate through the string tracking current character and count.
• Build the result as you go.
6. Matrix Transpose
Description: Given an m × n matrix, produce its transpose (which is n × m).
Example:
Original: " #
1 2 3
4 5 6
Transposed:
1 4
2 5
3 6
7. Longest Common Prefix
Description: Given a list of strings, find the longest common prefix they share.
Example:
• Input: [“interview”, “internal”, “internet”]
• Output: “inter”
Hint:
• Compare characters at each position across all strings until a mismatch.
8. Word Frequency in a File
Description:
• Read a text file line by line.
• Count the occurrences of each word (case-insensitive).
• Print the top 5 most frequent words with their counts.
5
Al Akhawayn University - Spring 2025 School of Science and Engineering
Hint:
• Use a dictionary where the key is the word and the value is the count.
• Convert words to lowercase and strip punctuation for consistency.
9. Merging Two Files
Description:
• You have two files containing lists of names (one name per line).
• Create a new file that merges both lists in alphabetical order, removing duplicates.
Hint:
• Read lines into two lists or sets.
• Combine, remove duplicates, sort, then write the result to a new file.
10. Flatten a Nested List
Description: Flatten a list containing sub-lists of arbitrary depth into a single list.
Example:
• Input: [[1, 2], [3, [4, 5]], 6]
• Output: [1, 2, 3, 4, 5, 6]
11. Rotate a List In-Place
Description: Similar to rotating a list, but do it in place (i.e., modify the existing list
instead of creating a new one).
Example:
• Input list: [1, 2, 3, 4, 5], steps: 2
• Output (modified in place): [4, 5, 1, 2, 3]
Difficult Exercises
1. Coin Change (Fewest Coins)
Description: Given a list of distinct coin denominations and a target amount n, find
the fewest number of coins needed to make n. If it is impossible to form n with the
given coins, return −1.
Example:
• Coins: [1, 3, 4], Target: 6
6
Al Akhawayn University - Spring 2025 School of Science and Engineering
• One optimal way: (3, 3) → 2 coins.
2. Integer Partition (Counting Partitions)
Description: Given a positive integer n, determine in how many ways it can be parti-
tioned into a sum of positive integers, where order does not matter.
Example (n = 4):
(a) 3 + 1
(b) 2 + 2
(c) 2 + 1 + 1
(d) 1 + 1 + 1 + 1
That’s 5 partitions total (including the single 4 itself).
3. Longest Palindromic Substring
Description: Given a string, find the longest substring that is a palindrome.
Example:
• Input: "babad"
• Valid outputs: "bab" or "aba"
Hint: Try the expand-around-center approach or a DP approach.
4. Word Break Problem
Description: You have a dictionary (set) of valid words, e.g. {"leet", "code", "python", "is", "
and a string "leetcode". Determine if the string can be segmented into valid words
from the set.
Example:
• Input: s = "leetcode"
• Dictionary: {"leet", "code"}
• Output: True, because "leet" + "code"
5. Traveling Salesman Problem (TSP)
Description: Given a set of cities (nodes) and the distances between them, find the
shortest possible route that visits each city exactly once and returns to the starting
city.
Example:
• Suppose you have 4 cities: A, B, C, D, with a distance matrix (lower is better).
7
Al Akhawayn University - Spring 2025 School of Science and Engineering
• You must find a route, e.g. A → B → C → D → A, that has minimal total
distance.
Hint:
• Brute force: try all permutations of cities (complexity O(n!)).
• DP (Held-Karp): O(n2 2n ) for exact solutions.
6. Weighted Interval Scheduling
Description: You have n intervals, each with a start time, an end time, and a weight
(or value). Find the maximum total weight of non-overlapping intervals.
Example:
• Suppose intervals (start, end, weight):
• (1,3,4), (2,5,2), (4,6,5), (6,7,1)
• The best set might be (1,3,4) + (4,6,5) = total weight 9 (non-overlapping).
Hint:
• Sort intervals by end time.
• Use DP to decide: include an interval + best solution before its start, or skip it.
7. N-Queens Problem
Description: Place n queens on an n × n chessboard such that no two queens can
attack each other (no shared row, column, or diagonal).
Example (n = 4):
• One valid arrangement (using Q for queens, . for empty):
. Q . .
. . . Q
Q . . .
. . Q .
• Another arrangement is possible (2 total solutions for 4-Queens).
Hint:
• Use backtracking, placing one queen per row.
• Keep track of occupied columns and diagonals as you go.
8
Al Akhawayn University - Spring 2025 School of Science and Engineering
8. Maze Escape (Shortest Path)
Description: Represent a maze as a tuple of tuples, where 0 indicates open paths and
1 indicates walls. Find the shortest path from the start (0, 0) to the end (n − 1, n − 1).
Example (4x4 maze):
maze = (
(0, 1, 0, 0),
(0, 1, 0, 1),
(0, 0, 0, 1),
(1, 1, 0, 0)
)
Output: Coordinates of the shortest path, e.g. [(0,0), (1,0), (2,0), (2,1), (2,2), (3,2),
(3,3)], or indicate if no path exists.
How to Use These Exercises
• Introductory: Great for beginners to practice basic arithmetic, loops, conditionals,
and simple data structure operations.
• Medium: Involves deeper logic or multi-step checks (e.g., Sudoku) and may require
knowledge of nested data structures, more advanced loops and basic dynamic program-
ming.
• Difficult: These typically require algorithmic thinking (e.g., BFS/DFS for Maze, dy-
namic programming for Coin Change and Integer Partition). Perfect for more advanced
learners looking to improve their problem-solving skills.