Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python cast character to operation

Tags:

python

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
like image 532
Alex Spangher Avatar asked Dec 26 '22 17:12

Alex Spangher


2 Answers

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
like image 98
mdml Avatar answered Dec 28 '22 08:12

mdml


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 :)

like image 25
Joseph Victor Zammit Avatar answered Dec 28 '22 08:12

Joseph Victor Zammit