Creating a Custom Calculator
Your task is to create a Number
class that utilizes Python's magic methods (__add__
, __sub__
, __mul__
, __truediv__
) to perform mathematical operations. However, the class needs to be robust and be able to handle various exceptions that can occur during these operations:
If a division by zero is attempted, a
ZeroDivisionError
should be raised with aCannot divide by zero
message.If either of the inputs cannot be converted to a number, a
ValueError
should be raised with anInvalid number input
message.If the operator is not a
Number
, aTypeError
should be raised with anOperator must be a Number
message.Additionally, you should implement a custom exception,
UnsupportedOperatorError
that inherits fromValueError
, with a messageUnsupported operator
. This error should be raised if an operation is attempted that is not supported by the class. That includes__floordiv__
,__mod__
,__pow__
,__lshift__
,__rshift__
,__and__
,__xor__
,__or__
.
All of the valid magic methods should return a Number
object.
Note: Don’t forget to implement the __str__
magic method to return the value of the Number
.
Input | Output |
| 12 5 |
| Cannot divide by zero |
| Invalid number input |
| Unsupported operator |
| Operator must be a Number |
| 20 |
| Unsupported operator |
Constraints
Time limit: 2 seconds
Memory limit: 512 MB
Output limit: 1 MB