1

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)))
green diod
  • 1,399
  • 3
  • 14
  • 29
  • I think you should process unary and binary separatly, you want to get `5 - 7 = -5`? – Assem Dec 16 '15 at 14:41
  • @bigOTHER Yeah, that's what I want/get. Of course, I can make a separate loop for unary ops. But maybe there's a more Pythonic way/some standard library to do it. (In C++, you have bind1st and so on) – green diod Dec 16 '15 at 14:48
  • 1
    the alternative of bind1st in python is `functools.partial` but `lambda` do the job magically so prefer it. Yet, in your case , just separate it, in python base readabilty counts – Assem Dec 16 '15 at 15:02

1 Answers1

1

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)))
Assem
  • 11,574
  • 5
  • 59
  • 97