Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Mathematical Operations using Operators from a list

Say I have a list with mathematical operators in it, like this

operators = ['+','-','*','/']

And I am taking a random operator from here, like this

op = random.choice(operators)

If I take two numbers, say 4 and 2, how can I get Python to do the mathematical operation (under the name 'op') with the numbers?

like image 512
DW_0505 Avatar asked Jun 01 '26 22:06

DW_0505


2 Answers

You better do not specify the operators as text. Simply use lambda expressions, or the operator module:

import operator
import random

operators = [operator.add,operator.sub,operator.mul,operator.floordiv]
op = random.choice(operators)

You can then call the op by calling it with two arguments, like:

result = op(2,3)

For example:

>>> import operator
>>> import random
>>> 
>>> operators = [operator.add,operator.sub,operator.mul,operator.floordiv]
>>> op = random.choice(operators)
>>> op
<built-in function sub>
>>> op(4,2)
2

So as you can see, the random picked the sub operator, so it subtracted 2 from 4.

In case you want to define an function that is not supported by operator, etc. you can use a lambda-expression, like:

operators = [operator.add,lambda x,y:x+2*y]

So here you specified a function that takes the parameters x and y and calculates x+2*y (of course you can define an arbitrary expression yourself).

like image 53
Willem Van Onsem Avatar answered Jun 05 '26 01:06

Willem Van Onsem


You can use eval if you are absolutely certain that what you are passing to it is safe like so:

num1 = 4
num2 = 2
operators = ['+','-','*','/']
op = random.choice(operators)
res = eval(str(num1) + op + str(num2))

Just keep in mind that eval executes code without running any checks on it so take care. Refer to this for more details on the topic when using ast to do a safe evaluation.

like image 43
The Quantum Physicist Avatar answered Jun 05 '26 00:06

The Quantum Physicist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!