I have an array with a list of comparison operators. How can I randomly select one to use? I tried the following but failed.
from random import choice
logi = ["<",">","=="]
n=20
n2 = choice(range(1,100))
if n choice(logi) n2: print n2
Take a look at operator
:
import operator
logi = [operator.lt, operator.gt, operator.eq]
...
if choice(logi)(n, n2):
print n2
You want to take not the textual representation of the operator, but some functional representation. For this, the operator module is perfect:
import operator
logi = [operator.lt, operator.gt, operator.eq]
Then, you can just apply this function using choice
:
n = 20
n2 = choice(range(1,100))
if choice(logi)(n, n2):
print n2
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