I'm writing a simple Python program for a projecteuler question, and it involves generating a search space over operations, ex:
8 = (4 * (1 + 3)) / 2
14 = 4 * (3 + 1 / 2)
19 = 4 * (2 + 3) − 1
36 = 3 * 4 * (2 + 1)
I'm storing possible operations in an array:
op = ['+', '-', '*', '/']
I was wondering if there's any way in Python to cast a character to an operation, so I could simply do something like:
for operation in op:
num1 foo(operation) num2
You could use the operator
module to get the functionality you're looking for. The operator
module has "a set of efficient functions corresponding to the intrinsic operators of Python":
>>> import operator as op
>>> ops = {"+": op.add, "-": op.sub, "/": op.div, "*": op.mul}
>>> num1, num2 = 3, 6
>>> for name, fn in ops.iteritems():
... print "{} {} {} = {}".format(num1, name, num2, fn(num1, num2))
...
3 + 6 = 9
3 * 6 = 18
3 - 6 = -3
3 / 6 = 0
What do you think about:
In [1]: add = lambda x,y: x+y
In [2]: sub = lambda x,y: x-y
In [3]: mult = lambda x,y: x*y
In [4]: divs = lambda x,y: x/y
In [5]: ops = [add,sub,mult,divs]
In [6]: for op in ops:
...: print op(1,2)
...:
3
-1
2
0
UPDATE: after posting my answer I noticed @mdml 's answer - I think it's more elegant than mine TBH :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With