Mathematics
Fundamentals
Code that can take an integer, an operator, and another integer, in that order, and return 'the answer'.
For example, can take '3' '*' and '3' to give '9'.
Did I do it right? Is this kumite?
def calculator(a,b,c): try: return eval(str(a)+str(b)+str(c)) except ZeroDivisionError: return float('inf')
def calculator(sign:str = '+', n1:(float | int) = 0, n2:(float | int) = 0, exceptions_allowed: bool = False):"""The simplest calculator ever.First argument is sign, +, -, *, /, ** and % supported. Default is +.The next two arguments is n1 and n2. Integers, Floats and Complex numbers supported. Their defaults is 0.Other arguments is options.exceptions_allowed - if True, will return exception instead of 0 when error occurs. Default is False."""if not isinstance(sign, str):if not exceptions_allowed: return 0else: raise TypeError('Type of the sign must be string.')if not isinstance(n1, (int, float, complex)):if not exceptions_allowed: return 0else: raise TypeError('Type of the first number must be int, float or complex.')if not isinstance(n2, (int, float, complex)):if not exceptions_allowed: return 0else: raise TypeError('Type of the second number must be int, float or complex.')if sign not in "+-*/**%":if not exceptions_allowed: return 0else: raise TypeError('Sign must be +, -, *, /, ** or %.')if sign == "/" and n2 == 0:if not exceptions_allowed: return float('inf') #mathematically this is better, than x/0=0else: raise ZeroDivisionError('Can\'t divide by zero.')return eval(str(n1) + sign + str(n2)) #using universal and optimized, but dangerous and bugged solution- def calculator(a,b,c):
- try: return eval(str(a)+str(b)+str(c))
- except ZeroDivisionError: return float('inf')
test.assert_equals(calculator(1,"/", 0), float('inf')) test.assert_equals(calculator(42,"+", 11), 53) test.assert_equals(calculator(6, "-", 50), -44) test.assert_equals(calculator(32, "/", 2), 16) test.assert_equals(calculator(25, "*", 5), 125) test.assert_equals(calculator(11, '%', 5), 1)
test.assert_equals(calculator("/", 1, 0), float('inf'))test.assert_equals(calculator("+", 42, 11), 53)test.assert_equals(calculator("-", 6, 50), -44)test.assert_equals(calculator("/", 32, 2, exceptions_allowed=True), 16)test.assert_equals(calculator("*", 25, 5), 125)test.assert_equals(calculator(123, 2), 0)test.assert_equals(calculator('%', 11, 5), 1)- test.assert_equals(calculator(1,"/", 0), float('inf'))
- test.assert_equals(calculator(42,"+", 11), 53)
- test.assert_equals(calculator(6, "-", 50), -44)
- test.assert_equals(calculator(32, "/", 2), 16)
- test.assert_equals(calculator(25, "*", 5), 125)
- test.assert_equals(calculator(11, '%', 5), 1)