Katkat

Debug and Extend a Nested-Class Program

AmericanSoftware Engineer · Technical Screen

Last 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

  1. Debug: Modify add_price so that previous_price is correctly updated to the old last_price before the new price is assigned.
  2. Extend: Add a method get_average() to the PriceHistory class that returns the mean of the two prices currently stored.

Constraints

  • price will 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?