Level 1 Cells and formulas
Build a small spreadsheet class Spreadsheet with:
set_cell(name, text) -> None: storetextin cellname. 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=-A1or=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
A1changes every formula that depends on it, directly or through other cells. - Watch out:
A1is a different cell fromA10. - If formulas refer to each other in a loop (
A1needsA2,A2needsA1, or a cell needs itself), reading a cell whose evaluation runs into the loop must raiseValueError. (Rejecting the loop earlier, by raisingValueErrorfrom theset_cellcall 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