나는 이렇게 학습한다/Algorithm & SQL

1015. simple calculator

daco2020 2022. 10. 15. 12:26
반응형

You are required to create a simple calculator that returns the result of addition, subtraction, multiplication or division of two numbers.

Your function will accept three arguments: The first and second argument should be numbers. The third argument should represent a sign indicating the operation to perform on these two numbers.

if the variables are not numbers or the sign does not belong to the list above a message "unknown value" must be returned.

Example:

calculator(1, 2, '+') => 3
calculator(1, 2, '$') # result will be "unknown value"



Solution:

def calculator(*args):
    x, y, op = list(map(str, args))
    if not validator(x, y, op):
        return "unknown value"
    return eval(f"{x}{op}{y}")

def validator(x, y, op):
    return x.isdigit() and y.isdigit() and op in "+-*/"


반응형