← Back to Chapter 5 Chapter 5 Practical Exam: Collections
30:00

Chapter 5 Practical Exam

Demonstrate your mastery of Python collections!

Problems
3
Difficulty
Medium
Time Limit
30 min
Solved
0/3

Problem 1: List Rotator

Medium

Description

Create a function rotate_list(lst, k) that rotates a list to the right by k positions.

For example, rotating [1, 2, 3, 4, 5] by 2 gives [4, 5, 1, 2, 3].

Requirements:

  • Return a new list (don't modify the original)
  • Handle k larger than list length
  • Handle empty lists (return empty list)
  • Handle negative k (rotate left instead)

Example

rotate_list([1, 2, 3, 4, 5], 2) # Returns: [4, 5, 1, 2, 3] rotate_list([1, 2, 3], 5) # Returns: [2, 3, 1] (5 % 3 = 2) rotate_list([1, 2, 3], -1) # Returns: [2, 3, 1] (rotate left) rotate_list([], 3) # Returns: []
Your Solution
Test Results
Click "Run Tests" to check your solution...

Hint

Use modulo (%) to handle k larger than list length. Slicing with negative indices makes this elegant: lst[-k:] + lst[:-k]

Problem 2: Unique Counter

Medium

Description

Create a function count_unique(lst) that returns a tuple containing:

  • The count of unique elements
  • A sorted list of the unique elements

Use sets to find unique elements efficiently!

Example

count_unique([1, 2, 2, 3, 3, 3]) # Returns: (3, [1, 2, 3]) count_unique(["a", "b", "a", "c"]) # Returns: (3, ['a', 'b', 'c']) count_unique([]) # Returns: (0, []) count_unique([5, 5, 5]) # Returns: (1, [5])
Your Solution
Test Results
Click "Run Tests" to check your solution...

Hint

Convert to set for unique elements, then sorted() for the sorted list. Return as a tuple: (len(unique_set), sorted(unique_set))

Problem 3: Tuple Merger

Medium

Description

Create a function merge_tuples(t1, t2) that takes two tuples of equal length and returns a list of tuples, where each tuple contains elements from the same index.

This is essentially implementing the zip() function!

Requirements:

  • If tuples have different lengths, only merge up to the shorter length
  • Return an empty list if either tuple is empty

Example

merge_tuples((1, 2, 3), ('a', 'b', 'c')) # Returns: [(1, 'a'), (2, 'b'), (3, 'c')] merge_tuples(('x', 'y'), (10, 20)) # Returns: [('x', 10), ('y', 20)] merge_tuples((1, 2, 3), ('a',)) # Returns: [(1, 'a')] merge_tuples((), (1, 2)) # Returns: []
Your Solution
Test Results
Click "Run Tests" to check your solution...

Hint

Use min(len(t1), len(t2)) to find the shorter length. Loop through indices and create tuples: [(t1[i], t2[i]) for i in range(min_len)]