Review a Hand-Rolled Python CSV Serializer for Correctness and Performance Bugs
Company: Mercor
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Technical Screen
You are reviewing this Python function, which is meant to turn a table (a list of rows, each row a list of cells) into CSV text:
```python
def to_csv(table):
output = ""
for row in table:
for cell in row:
output += cell
output += ","
output += "\n"
return output
```
Spot the issues with this code. For each issue, give an input that triggers it and explain what goes wrong. Then show how you would fix the function.
```hint Read it back
Feed the output to a standard CSV reader in your head and check whether you get the original table back, cell for cell. Then try cells that contain the characters CSV itself uses.
```
```hint Beyond correctness
Some issues only show up with large tables, or with cells that are not strings.
```
### Clarifying Questions
- Which CSV conventions must the output follow: comma delimiter, double-quote quoting, CRLF or LF line endings? Who consumes the file: a spreadsheet application, another service, a standard parser?
- What cell types can appear: only strings, or also numbers, `None`, dates and booleans?
- Can rows have different lengths, and is there a header row?
- How large can a table be? Must the output be written to a file or an HTTP response as it is produced?
### What a Strong Answer Covers
- Field and record separators: whether each line yields the right number of fields when read back
- The cost of building the output string, and how Python's string semantics affect it
- Behavior on cells that are not strings
- Quoting and escaping of cell contents that collide with CSV syntax
- A corrected implementation, preferably using the standard library, and a way to test it
### Follow-up Questions
- How would you stream a very large table to a file or an HTTP response without building the whole string in memory?
- A user opens the exported file in a spreadsheet application, and a cell that starts with `=` is evaluated as a formula. What is the risk, and how would you mitigate it?
- How would you test the function so that quoting bugs are caught automatically?
Overview: A code review question on a short Python function that turns a table of rows into CSV text. Candidates must find its correctness and performance problems and write a fixed version, which tests delimiter handling, string building in Python, non-string cells, CSV quoting and escaping rules, and how to verify the fix.
Read the full Mercor Software Engineer interview experience this question came from