Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Alternative to passing Greater Than sign as an argument

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading