Home > Blockchain >  Can we get comparison operator from user config and compare it with python in fewer steps?
Can we get comparison operator from user config and compare it with python in fewer steps?

Time:04-02

I have to compare a numeric column in table with any dynamic input condition specified in the config. So the comparison operator may come like > or >= and <= or < with upper and lower limit values.

Say I have table field value as 100

and I may get any 2 comparison operators like >= and <= from config file

and any upper and lower limit values like 90 and 110 from config file

Now I have to write a code that compares the value 100 with dynamic config condition like

if 90 >= 100 <= 110:

How can we achieve this? can we use anything like eval or something?

UPDATE: config file will look like

limit_condition = {'>=':90,'<':110}

or

limit_condition = {'>':90,'<':110}

or

limit_condition = {'>':90,'<=':110}

or

limit_condition = {'>=':90,'<=':110}

There may be a chance that only upper limit or lower limit alone they can give. So it should adopt for that too!

CodePudding user response:

I would suggest to define a comparison function that depends on the config file:

def create_comparison_function(config):
    # analyse configuration
    def comp_fun(number):
        # define operation depending on config; example result:
        return c1 <= number
    return comp_fun

Then use this method to create your comparison function and use it

comp_fun = create_comparison_function(config)
for n in numbers:
   if comp_fun(n):
        # do something
   else:
        # do something else

CodePudding user response:

I got the fewer code to do this!

all(
        [
            limit_condition['>='] >= 100 if limit_condition.get('>=') else limit_condition['>'] > 100 if limit_condition.get('>') else True,
            limit_condition['<='] <= 100 if limit_condition.get('<=') else limit_condition['<'] < 100 if limit_condition.get('<') else True
        ]
    )

CodePudding user response:

Still another one:

ops = {
       "<": lambda a, b: a < b,
       ">": lambda a, b: a > b,
       "<=": lambda a, b: a <= b,
       ">=": lambda a, b: a >= b,
       "==": lambda a, b: a == b
       }        

config = {'>=': 90,'<': 110}
numbers = [80, 100, 120]

for n in numbers:
    if all([ops[op](n, c) for op, c in config.items()]):
        print(f"{n} is ok")
    else:
        print(f"{n} is nok")
  • Related