Search code examples
pythonunary-operatorbinary-operators

Python binary to unary function


Following this thread about iterating through a sequence of operators, I want also to take care of unary operators in the same sequence. I used a lambda function to get rid of the second argument but are there special purpose tools/libraries for that in Python?

a, b = 5, 7
for op in [('+', operator.add), ('-', lambda x, y: operator.neg(x))]:
    print("{} {} {} = {}".format(a, op[0], b, op[1](a, b)))

Solution

  • Just separate the processing of binary and unary operators.

    a, b = 5, 7
    # binary ops
    for op in [('+', operator.add), ('-', operator.sub]:
        print("{} {} {} = {}".format(a, op[0], b, op[1](a, b)))
    
    #unary ops
    for op in [('-', operator.neg]:
        print("{} {} = {}".format(op[0], a, op[1](a)))