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

P

palewire

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

Paul Rubin

palewire said:
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.

Didn't we just have a huge thread about that? Using a special null
value is often (not always) a code smell. But anyway (untested):

def compare(a,b):
if a is None and b is None: # I'm guessing you meant this
return "No data"
if a == b:
return "Stayed the same" if a != 0 else "Never had"
elif a < b:
return "gained"
else:
# we know here that a > b
return "Lost some" if b > 0 else "Lost all"

I don't know what you intended to do in the case where exactly one of
(a,b) is None, so I'll leave that to you.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top