Debug and Extend a Nested-Class Program
AmericanSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to identify state synchronization issues in nested class structures and implement a thread-safe extension to existing class logic.
Problem Statement
You are working on a MarketTracker system that monitors price volatility. The system uses a nested PriceHistory class to track the last two prices received. However, the system currently reports an incorrect get_volatility() value because the state is not updated correctly when new prices are added.
Current Implementation
class MarketTracker:
def __init__(self):
self.history = self.PriceHistory()
class PriceHistory:
def __init__(self):
self.last_price = 0
self.previous_price = 0
def add_price(self, price):
self.last_price = price
def get_volatility(self):
# Currently calculates difference between last and 0
return abs(self.last_price - self.previous_price)
def update(self, price):
self.history.add_price(price)
Task
- Debug: Modify
add_priceso thatprevious_priceis correctly updated to the oldlast_pricebefore the new price is assigned. - Extend: Add a method
get_average()to thePriceHistoryclass that returns the mean of the two prices currently stored.
Constraints
pricewill always be a positive integer.- Assume only two prices are stored at any time.
Example
tracker = MarketTracker()
tracker.update(10)
tracker.update(20)
# After update(20), previous_price is 10, last_price is 20.
# get_volatility() should return 10.
# get_average() should return 15.0.
Hints
Hint 1
Before overwriting the `last_price` variable, store its current value in `previous_price`.
Hint 2
Ensure that the `add_price` method updates both class attributes in the correct sequence to prevent data loss.
Hint 3
For the average, perform the calculation using floating-point division to ensure accuracy.
Follow-up questions
- How would you modify this code to track the last N prices instead of just the last two?
- If this tracker were accessed by multiple threads, what specific parts of the code would require synchronization?
- How would you refactor this to avoid using a nested class if you wanted to improve the unit testability of the history tracking logic?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.