We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Calculator with Method Chaining

Difficulty: Easy


Problem Description

Design a Calculator class that provides mathematical operations of addition, subtraction, multiplication, division, and exponentiation, allowing for method chaining. The constructor accepts an initial value for result.


Key Insights

  • The Calculator class should support method chaining, meaning each operation returns the instance itself.
  • Proper error handling must be implemented for division by zero.
  • The result should be returned with a precision of up to 10^-5.

Space and Time Complexity

Time Complexity: O(1) for each operation since they involve basic arithmetic. Space Complexity: O(1) as we are only storing a single result value.


Solution

The solution involves creating a Calculator class that maintains an internal result variable, initialized in the constructor. Each mathematical operation (add, subtract, multiply, divide, power) modifies this result and then returns the instance of the Calculator to allow for chaining. The getResult method retrieves the current value of result. Error handling is implemented specifically for division to prevent division by zero.


Code Solutions

class Calculator:
    def __init__(self, initial_value):
        self.result = initial_value

    def add(self, value):
        self.result += value
        return self

    def subtract(self, value):
        self.result -= value
        return self

    def multiply(self, value):
        self.result *= value
        return self

    def divide(self, value):
        if value == 0:
            raise ValueError("Division by zero is not allowed")
        self.result /= value
        return self

    def power(self, value):
        self.result **= value
        return self

    def getResult(self):
        return self.result
← Back to All Questions