~/problems / Graphs / Topological sort (Kahn's)

Spreadsheet with formula dependencies

medium 2 levels ~45 min OpenAI

Level 1 Cells and formulas

Build a small spreadsheet class Spreadsheet with:

  • set_cell(name, text) -> None: store text in cell name. Cell names are uppercase letters followed by digits (A1, B12, AA7).
  • get_cell(name) -> float: the cell's current value.

text is either

  • a plain number, like "42", "-3" or "2.5", or
  • a formula starting with =, like "=A1 + 2 * (B3 - 1)". A formula may contain cell names, non-negative number literals, + - * /, parentheses and spaces. Normal precedence applies (* and / before + and -, left to right). Formulas never use a unary minus (like =-A1 or =2*-3), so every - in a formula is a subtraction.

Rules:

  • A cell that was never set has the value 0.0, both when read directly and when a formula refers to it.
  • Values always reflect the current contents: changing A1 changes every formula that depends on it, directly or through other cells.
  • Watch out: A1 is a different cell from A10.
  • If formulas refer to each other in a loop (A1 needs A2, A2 needs A1, or a cell needs itself), reading a cell whose evaluation runs into the loop must raise ValueError. (Rejecting the loop earlier, by raising ValueError from the set_cell call that would close it, is also accepted here. Level 2 requires that.)

Tests never divide by zero. Answers are compared with a small tolerance.

s = Spreadsheet()
s.set_cell("A1", "1")
s.set_cell("A2", "2")
s.set_cell("A3", "=A1 + A2")      # 3
s.set_cell("A4", "=A3 * A2")      # 6
s.get_cell("A4")                  # 6.0
s.set_cell("A1", "10")
s.get_cell("A4")                  # 24.0
s.get_cell("Z9")                  # 0.0

Level 2 unlocks when level 1 passes.

Topic: Topological sort (Kahn's). BFS over in-degree-0 nodes; leftover nodes mean a cycle.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc