반응형
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 "+-*/"
반응형
'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글
1017. Enumerable Magic - Does My List Include This? (0) | 2022.10.17 |
---|---|
1016. Multiplication table for number (0) | 2022.10.17 |
1014. Find Multiples of a Number (0) | 2022.10.14 |
1013. Area or Perimeter (0) | 2022.10.13 |
1012. All Star Code Challenge #18 (0) | 2022.10.12 |