Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly use a Comparison operator?

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
like image 636
Ahdee Avatar asked Oct 17 '13 15:10

Ahdee


2 Answers

Take a look at operator:

import operator
logi = [operator.lt, operator.gt, operator.eq]

...

if choice(logi)(n, n2):
    print n2
like image 98
arshajii Avatar answered Oct 11 '22 15:10

arshajii


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
like image 33
val Avatar answered Oct 11 '22 15:10

val