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

Rhodri James rhodri at wildebst.demon.co.uk
Mon Jul 6 22:11:43 EDT 2009


On Tue, 07 Jul 2009 02:25:13 +0100, palewire <ben.welsh at gmail.com> wrote:

> 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.

It depends on what you want to do with the information.  If you're doing
different things on each case, you might as well do it with an if-chain,
though you could make it a bit tidier:

> def compare(a, b):
>     if not a and not b:

Did you mean "if a is None or b is None:" here?

>         return "No data"
>     else:
>         if a == 0 and b == 0:

This will never fire, because it will always be
caught by the test above.

>             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"

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


Alternatively you can do something like the (deprecated) cmp and a
dispatch table:

CMP_TABLE = [ "Gained", "Stayed the same", "Lost Some", "Lost All"]

def compare(a, b):
     if a is not None or b is not None:
         return "No data"
     c = cmp(a, b) + 1
     if c == 2 and b == 0:
         c = 3
     return CMP_TABLE[c]

There's no cmp() in Python 3.x so you'd have to roll your own.  At
that point you might as well revert to the if-chain, since it'll be
a lot easier to understand when you come back to it in six months
time.


-- 
Rhodri James *-* Wildebeest Herder to the Masses



More information about the Python-list mailing list