← Questions

Robust Python generator, then a weighted one

0
GoogleCodingLast asked Sep 2025

A coding interview question asked in Google's onsite coding round, last asked Sep 2025. It tests python, generators and testing.

Write a Python generator that yields the integers of an input sequence, robust to messy input, with a full set of unit tests. Then change it to yield items at random according to a weight for each, and test that the output distribution is right.

Part 1: a robust generator

  • iter_ints(items: Iterable) -> Iterator[int] — yield each integer in input order, duplicates included. Read the input lazily so a very large input (a file, another generator) is never loaded into memory at once. Decide and document the behaviour for edge cases; one reasonable choice:
    • None is skipped;
    • an empty input yields nothing;
    • bool and non-integers ("3", 2.5) raise TypeError naming the position, or are skipped in a lenient mode;
    • a None input itself raises TypeError.
list(iter_ints([3, None, 3, 7]))   ->  [3, 3, 7]
list(iter_ints([]))                ->  []
list(iter_ints([1, "x"]))          ->  yields 1, then raises TypeError at index 1

Part 2: a weighted generator

  • weighted_stream(items: list, weights: list[float], rng=random) -> Iterator — yield items forever, each draw independent, choosing item i with probability weights[i] / sum(weights). Validate the inputs: equal lengths, non-negative weights, a positive total.
weighted_stream(["a", "b"], [3, 1])   # about 75% "a" and 25% "b" over many draws

Clarifying questions

  • Skip, convert or raise on None and on invalid items? Is there a strict and a lenient mode?
  • Should True count as the integer 1?
  • Is the input a list, or any iterable (possibly infinite)?
  • Part 2: with or without replacement? Can weights be zero, or change over time?

What a strong answer covers

  • A real generator (yield), so memory stays O(1) and iteration can stop early; errors raised at the item, not up front.
  • Clear, documented rules, and tests that pin each one: normal input, empty, all None, duplicates, order kept, bad types, a huge lazy input (a generator of 10^7 items) to show nothing is materialised.
  • Part 2: prefix sums of the weights plus bisect on rng.random() * total, O(log n) per draw after O(n) setup; or the alias method for O(1) draws.
  • Testing randomness: a seeded rng for deterministic tests, and a statistical test (frequencies within tolerance, or chi-squared) over many draws.
  • Edge cases: a zero weight is never drawn, one item, floating-point totals.

Follow-ups

  • Weights change while the stream runs.
  • Sample k distinct items by weight without replacement.
  • Make the first generator async, reading from a network stream.

Where it's asked

  • Google · Onsite coding · Last asked Sep 202545 min · Usually two rounds, mostly in person: whiteboard plus a Chromebook with Google Docs · No AI (a pilot code-comprehension round lets candidates use Gemini)

What it tests

python · generators · testing

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding