Search code examples
pythonvectorization

How do you check if something has declined by 10% without an if statement?


I am given two numbers x and y in Python, and I'm asked if y represents a 10% decrease from x.

What is the best way of doing this without an if-statement? I am looking to vectorize this operation, so it'd be good to have a branchless form.

The verbose check would be:

def check(x,y):
    if x < 0:
        return y < x*1.1
    else:
        return y < x*0.9

I considered

def check(x,y):
    return y < x * (1.1 if x < 0 else 0.9)

but that's just an inline if-statement.


Solution

  • If I understand the question correctly, I think this should work:

    def ten_percent_decrease(x: int, y: int):
        """
        check if y is 10% less than x
        """
        return (x - y) / abs(x) > 0.1
    

    Note: the code breaks if you give 0 for x. I'm not sure what you want the expected output to be in that case, but you can adjust it accordingly.