Python cast character to operation

python

Solution

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

Problem

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 ```

Original source