KatInterview

Five Python Fundamentals: Iteration, Collections, and Edge Cases

StringsModel answer
MediumModel answerStringspythonfundamentalsedge-cases

Last 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

  1. Repeat with separators: Write a function repeat_message(msg: str, n: int) -> str that returns the message repeated n times, separated by blank lines (two newlines between occurrences). If n ≤ 0, return an empty string.

  2. 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.

  3. FizzBuzz: Write a function fizzbuzz(n: int) -> None that prints the integers from 1 to n (inclusive), replacing multiples of 3 with "Fizz", multiples of 5 with "Buzz", and multiples of both with "FizzBuzz".

  4. 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.

  5. Second-largest unique: Write a function second_largest(nums: list[int]) -> int | None that returns the second-largest unique integer, or None if 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.