Five Python Fundamentals: Iteration, Collections, and Edge Cases
StringsModel answerLast updated
Write five short functions covering string repetition, list transformation, FizzBuzz, word counting, and finding the second-largest unique integer.
You are asked to implement five independent Python functions that test your understanding of basic data manipulation, iteration, and edge-case handling.
The Five Functions
-
Repeat with separators: Write a function
repeat_message(msg: str, n: int) -> strthat returns the message repeatedntimes, separated by blank lines (two newlines between occurrences). Ifn ≤ 0, return an empty string. -
Square and reverse: Write a function
square_and_reverse(nums: list[int]) -> list[int]that returns a new list containing the squares of the input integers, in reverse order. The original list must remain unchanged. -
FizzBuzz: Write a function
fizzbuzz(n: int) -> Nonethat prints the integers from 1 ton(inclusive), replacing multiples of 3 with "Fizz", multiples of 5 with "Buzz", and multiples of both with "FizzBuzz". -
Case-sensitive word count: Write a function
count_words(text: str) -> dict[str, int]that returns a dictionary mapping each whitespace-delimited word to its frequency. Words are case-sensitive. -
Second-largest unique: Write a function
second_largest(nums: list[int]) -> int | Nonethat returns the second-largest unique integer, orNoneif fewer than two distinct values exist.
Constraints
- All inputs fit comfortably in memory.
- Words are delimited by any whitespace (spaces, tabs, newlines).
- Function signatures and return types should match exactly.
What You Should Cover
- Correct implementation of each function
- Handling of edge cases (empty inputs, single elements, negatives, duplicates)
- Time and space complexity for each
- Testing strategy: what cases would you verify?
- Any pitfalls or common mistakes to avoid
Hints
Hint 1
Consider what happens when collections are empty or contain only one element.
Hint 2
Remember that Python's set automatically handles uniqueness, but order matters for the second-largest problem.
Hint 3
Think about whether you need to preserve the original input or if mutation is acceptable.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each function tests a different fundamental skill: string formatting, list comprehensions, conditional logic, dictionary aggregation, and set operations with ordering.
1. Repeat with Separators
Implementation:
def repeat_message(msg: str, n: int) -> str:
if n <= 0:
return ""
return "\n\n".join([msg] * n)
Key points:
- Build a list of
ncopies, then join with double newlines. - Edge case:
n ≤ 0returns empty string immediately. - Complexity: O(n · m) time where m is message length; O(n · m) space for the result.
Common mistake: Using a loop with manual concatenation is less idiomatic and can be O(n²) in some languages, though Python optimizes this reasonably well.
2. Square and Reverse
Implementation:
def square_and_reverse(nums: list[int]) -> list[int]:
return [x * x for x in reversed(nums)]
or equivalently:
def square_and_reverse(nums: list[int]) -> list[int]:
return [x * x for x in nums][::-1]
Key points:
- List comprehension creates a new list, leaving the original unchanged.
reversed()is an iterator (efficient), or slice[::-1]reverses in place.- Edge case: empty list returns empty list.
- Complexity: O(n) time, O(n) space.
Common mistake: Mutating the input with nums.reverse() before returning, which violates the immutability requirement.
3. FizzBuzz
Implementation:
def fizzbuzz(n: int) -> None:
for i in range(1, n + 1):
if i % 15 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
Key points:
- Check divisibility by 15 first to avoid redundant checks.
- Alternatively, build the string conditionally:
output = ("Fizz" if i % 3 == 0 else "") + ("Buzz" if i % 5 == 0 else "") or str(i). - Edge case:
n = 0prints nothing (range is empty). - Complexity: O(n) time, O(1) space.
Common mistake: Checking % 3 and % 5 without handling % 15 first, leading to incorrect output for multiples of both.
4. Case-Sensitive Word Count
Implementation:
def count_words(text: str) -> dict[str, int]:
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
return counts
or using collections.Counter:
from collections import Counter
def count_words(text: str) -> dict[str, int]:
return dict(Counter(text.split()))
Key points:
split()with no argument splits on any whitespace and handles multiple spaces, tabs, newlines.- Case-sensitive: "Hello" and "hello" are distinct.
- Edge case: empty string returns empty dict.
- Complexity: O(n) time where n is the number of characters; O(w) space where w is the number of unique words.
Common mistake: Using split(' ') instead of split(), which fails on tabs or multiple spaces.
5. Second-Largest Unique
Implementation:
def second_largest(nums: list[int]) -> int | None:
unique = list(set(nums))
if len(unique) < 2:
return None
unique.sort(reverse=True)
return unique[1]
Key points:
- Convert to set to remove duplicates, then back to list for sorting.
- Edge cases: empty list, single element, or all duplicates return
None. - Complexity: O(n log n) time due to sorting; O(n) space for the unique set.
Alternative O(n) approach (single pass):
def second_largest(nums: list[int]) -> int | None:
if not nums:
return None
first = second = float('-inf')
for num in nums:
if num > first:
second = first
first = num
elif num > second and num != first:
second = num
return second if second != float('-inf') else None
Common mistakes:
- Forgetting duplicates:
[5, 5, 3]should return3, not5. - Not handling cases with fewer than two unique values.
Testing Strategy
- Repeat message:
n = 0,n = 1,n = 3, empty message. - Square and reverse: empty list, single element, negatives, verify original unchanged.
- FizzBuzz:
n = 0,n = 15,n = 1. - Word count: empty string, single word, repeated words, mixed whitespace.
- Second largest: empty, one element, all duplicates,
[1, 2],[5, 5, 3, 3, 1].
Operational Trade-offs
- Idiomatic vs. performance: List comprehensions and
Counterare Pythonic and readable; manual loops can be faster for very large inputs but sacrifice clarity. - Mutability: Always clarify whether inputs can be modified. Here, immutability is safer and expected.
- Edge-case verbosity: Explicit checks (
if n <= 0) improve robustness and make intent clear, even if the default behavior might "just work."
Summary
These exercises validate fundamental skills: iteration patterns, collection manipulation, conditional logic, and edge-case reasoning. A strong answer demonstrates correct implementations, articulates complexity, and proactively addresses boundary conditions and common pitfalls.