J French
J French

Reputation: 197

Better way of checking if number fall within a specific range, applying a function to each if they do not?

Both g1 an g2 are random integers.

I am calling a getValue() method on both which multiplies them by another integer.

I'm trying to check if the result of getvalue(g1) and getValue(g2) are greater than 20.

If they both equal to 0, and if they are less than 20, I apply another function to each of them.

Does anyone have a more concise way of doing this?


 def fitness(self):
      g1, g2 = self.select()

      if self.getValue(g1) > 20:
        g1 = 0 
      else:
        g1 = self.getBenifit(g1)

      if self.getValue(g2) > 20:
        g2 = 0 
      else:
        g2 = self.getBenifit(g2)

      return g1, g2

Upvotes: 0

Views: 57

Answers (2)

alani
alani

Reputation: 13079

As another answer points out, you can use syntax like this:

value_if_true if condition else value_if_false

Separately from that, you obviously have some repeated code here. For only two items, it is probably not worth doing any differently, but if you get many more, you should consider making a function and calling it for each item. Just to illustrate the point, you might end up with something like this:

def my_conversion(self, g):
    return 0 if self.getValue(g) > 20 else self.getBenifit(g)

def fitness(self):
    g1, g2 = self.select()
    return self.my_conversion(g1), self.my_conversion(g2)

Or if self.select() might return a large number of items, here is another possibility. In this case, maybe you don't need a separate function, but you do have a loop here instead.

def fitness(self):
    return tuple((0 if self.getValue(g) > 20 else self.getBenifit(g))
                  for g in self.select())

These are just options to bear in mind, and obviously I am not claiming that it clarifies the code in the case of only two items.

Upvotes: 1

bhristov
bhristov

Reputation: 3197

You can shorten the if statements like this:

    g1 = 0 if self.getValue(g1) > 20 else self.getBenifit(g1)
    g2 = 0 if self.getValue(g2) > 20 else self.getBenifit(g2)

Upvotes: 1

Related Questions