Alternative to passing Greater Than sign as an argument

Question:

My function :

def check(list,num):

  check if there is list[x] > list[0]+num  # in case num is positive
  OR if there is list[x] < list[0]+num  # in case num is negative

So I can send 50 to check if we are up 50, or -50 to check if we are down 50.

The only way I see to do this is ugly :

  for x in list:
    if num > 0 :
       if x > list[0] + num : do something
    if num < 0 :
       if x < list[0] + num : do something

Since i can not send > as an argument and use a single line, I am looking for a more elegant way.

Asked By: gotiredofcoding

||

Answers:

If you are trying to pass the comparison function as an argument you can use the operator module

import operator
operator.lt  #  <
operator.gt  #  >
operator.le  #  <=
operator.ge  #  >=

In your case you could refactor to

def function(comparison):
  for x in values:
    if comparison(num, 0) and comparison(x, values[0] + num):
      # do something

then you could call it as

function(operator.lt)  # positive check
function(operator.gt)  # negative check
Answered By: Cory Kramer

Another simple code example:

def f(ll, nn):
   
    for i in ll:
        if ((abs(nn))==nn) and (i > (ll[0]+nn)):
            print("+",)
            
        elif ((abs(nn))!=nn) and (i < (ll[0]+nn)):
            print("-")
            
        else:
            print("*")
    


f([100,-200,300,-400], +100)
Answered By: Malo
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.