Search code examples
pythondictionarycalculatoroperation

Are there mathematical functions to add, substract, multiply, power, or, and that works on multiple elements passed to fuction?


The function should take multiple args and make certain mathematical operations on them (+, -, *, **, |, &). + is a deafult operator. Mathematical fuction is connected to dictionary. Below is what I,ve made so far. But i have problem with mathematical operations (dont take multiple args). Can anyone help? Examples args: 1, 3, 5, operation='-' --> result: 1 - 3 - 5 = -7

def multi_calculator(*args: int, operation='+'):
    import operator
    ops = {
        '+': sum,
        '-': operator.sub,
        '*': operator.mul,
        '**': operator.pow,
        '|': operator.or_,
        '&': operator.and_,
    }

    if operation not in ops:
        result = 'Unknown operator'
    elif len(args) == 0:
        result = 0
    elif len(args) == 1:
        result = args[0]
    else:
        result = ops[operation](args)
    return result


print(multi_calculator(1, 2, 3, operation='-'))

Solution

  • You can use functools.reduce:

    import operator
    import functools
    
    def multi_calculator(*args: int, operation='+'):
        
        ops = {
            '+': operator.add,
            '-': operator.sub,
            '*': operator.mul,
            '**': operator.pow,
            '|': operator.or_,
            '&': operator.and_,
        }
    
        if operation not in ops:
            result = 'Unknown operator'
        elif len(args) == 0:
            result = 0
        elif len(args) == 1:
            result = args[0]
        else:
            result = functools.reduce(ops[operation], args)
        return result
    
    
    print(multi_calculator(1, 2, 3, operation='-'))