How to return value for different layers of (x,y) levels
Question: My problem is the following. I a functional requirement where the user can
choose between 3 or 5 levels and a value will be returned according to which
level (x,y) belong.

for example in 3 levels we have

    
    
    def f(x,y):
            if (0 <= x <= 0.3 and 0 <= y <= 1) or (0.3 <= x <= 1 and 0 <= y <= 0.3):
                return 1
            elif (0.3 < x <= 0.6 and 0.3 < y <= 1) or (0.6 <= x <= 1 and 0.3 < y <= 0.6):
                return 2
            else:
                return 3
    

for 5 levels we would have 5 if branches and so on.

I was wondering which is the best way(or a good) to do that in Python with the
DRY principle. My mind is short of short circuited right now.


Answer: So first, we can recognize that we can rewrite your program as:

    
    
    def f(x, y):
        if min(x, y) <= 0.3:
            return 1
        elif min(x, y) <= 0.6:
            return 2
        else:
            return 3
    

We can then format this into a for loop fairly easily:

    
    
    from __future__ import division
    
    def f(x, y, n=3):
        for i in range(1, n+1):
            if min(x, y) <= i/n:
                return i
        else:
            return n
    

We could also write a math equation for this and drop the for loop:

    
    
    def f(x, y, n=3):
        return int(min(x, y) * n) + 1
    

This last equation will fail when `x == 1` or `y == 1`. You should probably
just either make a special case for that, or also perform a
`max(result_so_far, n)` as well.

