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

Make a function that does arithmetic!

daco2020 2022. 7. 31. 23:03
반응형

Given two numbers and an arithmetic operator (the name of it, as a string), return the result of the two numbers having that operator used on them.

a and b will both be positive integers, and a will always be the first number in the operation, and b always the second.

The four operators are "add", "subtract", "divide", "multiply".

A few examples:(Input1, Input2, Input3 --> Output)

5, 2, "add"      --> 7
5, 2, "subtract" --> 3
5, 2, "multiply" --> 10
5, 2, "divide"   --> 2.5

 

Solution:

def arithmetic(a, b, operator):
    return (operator == "add" and a+b)\
           or (operator == "subtract" and a-b)\
           or (operator == "multiply" and a*b)\
           or (operator == "divide" and a/b)

 

Other Solution: use dictionary

def arithmetic(a, b, operator):
    return {
        'add': a + b,
        'subtract': a - b,
        'multiply': a * b,
        'divide': a / b,
    }[operator]

 

Other Solution: use operator

from operator import add, mul, sub, truediv


def arithmetic(a, b, operator):
    ops = {'add': add, 'subtract': sub, 'multiply': mul, 'divide': truediv}
    return ops[operator](a, b)

 

 

반응형

'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글

Sort the odd  (0) 2022.08.02
Form The Minimum  (0) 2022.08.02
Printer Errors  (0) 2022.07.31
Build Tower  (0) 2022.07.29
Highest Scoring Word  (0) 2022.07.28