Creating a Calculator Class in Python

This technical problem explains how to create a calculator class in Python that can perform addition, subtraction, multiplication, and division operations. The calculator takes two operands (numbers) and an operator as input, and returns the result of the operation.

Problem

Implement a basic calculator class that can perform addition, subtraction, multiplication, and division operations. The calculator should take two operands (numbers) and an operator as input, and return the result of the operation.
Example input:
calculator = Calculator()
result = calculator.calculate(10, "+", 5)
print(result)
Example output:
15

Solution

This solution is in Python. Our A.I. can create solutions in multiple languages.
by kayakane
class Calculator:
    def __init__(self):
        pass

    def calculate(self, num1, operator, num2):
        if operator == "+":
            return num1 + num2
        elif operator == "-":
            return num1 - num2
        elif operator == "*":
            return num1 * num2
        elif operator == "/":
            return num1 / num2
        else:
            return "Invalid operator"

calculator = Calculator()
result = calculator.calculate(10, "+", 5)
print(result)



The solution is optimal because it is simple and easy to understand. It is also easy to add more operators if needed.


A.I. Evaluation of the Solution

The candidate's solution is complete and solves the problem. The approach is straightforward and easy to understand.

Evaluated at: 2022-11-19 16:16:08