Airbnb Python Code Review: Spot Bugs, Style Issues, and Performance Problems
Question Details
Round 1 Code Review
You are shown the following Python function and asked to critique it. Identify all bugs, style issues, and performance problems. Then rewrite it cleanly.
python
def get_available_listings(listings, checkin, checkout, max_price=None):
result = []
for i in range(len(listings)):
l = listings[i]
if l['available'] == True:
if l['checkin'] <= checkin and l['checkout'] >= checkout:
if max_price != None:
if l['price'] <= max_price:
result.append(l)
else:
result.append(l)
**return** result
Issues to find:
- == True should be is True or just truthy check
- != None should be is not None
- range(len(...)) anti-pattern; iterate directly
- Nested if chains can be flattened with and
- No type hints or docstring
- Does not validate that checkin < checkout
Follow-ups
- Rewrite the function using a list comprehension. What are the tradeoffs?
- If
listingshas 1 million entries, how would you make this faster using indexing? - How would you write unit tests for this function, including edge cases?
- How does Python's short-circuit evaluation affect the order of your
andconditions?
Full Details
Round 1 Code Review
You are shown the following Python function and asked to critique it. Identify all bugs, style issues, and performance problems. Then rewrite it cleanly.
python
def get_available_listings(listings, checkin, checkout, max_price=None):
result = []
for i in range(len(listings)):
l = listings[i]
if l['available'] == True:
if l['checkin'] <= checkin and l['checkout'] >= checkout:
if max_price != None:
if l['price'] <= max_price:
result.append(l)
else:
result.append(l)
**return** result
Issues to find:
- == True should be is True or just truthy check
- != None should be is not None
- range(len(...)) anti-pattern; iterate directly
- Nested if chains can be flattened with and
- No type hints or docstring
- Does not validate that checkin < checkout
Follow-ups
- Rewrite the function using a list comprehension. What are the tradeoffs?
- If
listingshas 1 million entries, how would you make this faster using indexing? - How would you write unit tests for this function, including edge cases?
- How does Python's short-circuit evaluation affect the order of your
andconditions?