Looking for a slick way to classify relationship between two numbers, without tons of if/else

palewire ben.welsh at gmail.com
Mon Jul 6 21:25:13 EDT 2009



In my application, I'd like to have a function that compares two values,
either of which may be null, and then classify the result depending on
whether one is higher or lower than the other.

I find myself writing something clunky like this, and I'm curious whether
anyone might know a more elegant way for parsing this out.

def compare(a, b):
    if not a and not b:
        return "No data"
    else:
        if a == 0 and b == 0:
            return "Never had"
        else:
            if a == b:
                return "Stayed the same"
            elif a < b:
                return "Gained"
            elif a > b and b > 0:
                return "Lost Some"
            elif a > b and b == 0:
                return "Lost All"

If there's some obvious way to search for this solution online, feel free to
slap me with that. I tried digging around on Google and couldn't come up
with much.

Thanks much.
-- 
View this message in context: http://www.nabble.com/Looking-for-a-slick-way-to-classify-relationship-between-two-numbers%2C-without-tons-of-if-else-tp24365710p24365710.html
Sent from the Python - python-list mailing list archive at Nabble.com.




More information about the Python-list mailing list