Spreadsheets are powerful tools for organizing and calculating data. In this post, we’ll walk through how to build a basic spreadsheet engine in Python that supports cell updates, resets, and formula evaluation.
๐งฉ Problem Overview
We need to implement a spreadsheet with:
26 columns labeled
'A'to'Z'A user-defined number of rows
Each cell can store an integer between
0and10^5Support for formulas like
=A1+B2+5, where operands can be cell references or integers
๐ ️ Class Design
We’ll use a dictionary to store only the cells that have been explicitly set. Unset cells are treated as having a value of 0.
class Spreadsheet:
def __init__(self, rows: int):
self.mpp = {}
def setCell(self, cell: str, value: int) -> None:
self.mpp[cell] = value
def resetCell(self, cell: str) -> None:
self.mpp[cell] = 0
def getValue(self, formula: str) -> int:
new_text = formula.replace("=", "+")
parts = new_text.split('+')
total = 0
for part in parts:
part = part.strip()
if part in self.mpp:
total += self.mpp[part]
elif part.isdigit():
total += int(part)
return total
๐งช Example Usage
# Initialize spreadsheet with 10 rows
obj = Spreadsheet(10)
# Set cell A1 to 10
obj.setCell("A1", 10)
# Reset cell B! (treated as valid input, reset to 0)
obj.resetCell("B!")
# Evaluate formula "A1" (no '=' or '+', treated as single cell reference)
param_3 = obj.getValue('A1')
print(param_3) # Output: 10
๐ Notes
The
getValuemethod replaces=with+to normalize the formula, then splits it by+.Each part is checked: if it’s a digit, it’s added directly; if it’s a cell reference, its value is fetched from the dictionary.
Unset cells default to
0usingdict.get()logic.
๐ฆ Enhancements
This basic engine can be extended to support:
Cell ranges like
A1:A3More operators (
-,*,/)Dependency tracking and auto-updates
This implementation is efficient and handles up to 10⁴ operations smoothly. Perfect for interview prep or building lightweight spreadsheet logic into a Python app.
Let me know if you'd like to turn this into a Markdown post, add visuals, or integrate it with a GUI or web interface.
Comments
Post a Comment