Looking for a short way of doing a division where the large number is always the numerator. Is there a simpler way of doing it other than this?
def divide(A, B):
if A > B:
return A/B
else:
return B/A
CodePudding user response:
there is a better way to do so :
def divide(A,B):
return max(A,B)/min(A,B)
CodePudding user response:
If you don't like if
statements and you want to avoid redundant comparisons, then you can do this:
from operator import truediv
def divide(a, b):
return truediv(*sorted([a, b], reverse=True))
Or, alright, the slightly less silly way of doing this:
def divide(a, b):
a, b = sorted([a, b])
return b / a
But... don't. Your way is the simplest, most obvious way to do it.
CodePudding user response:
Some more ways...
The straight-forward one that oddly nobody showed yet:
def divide(A, B):
return A/B if A > B else B/A
Short one, if your values are positive:
def divide(A, B):
return max(A/B, B/A)
Shorter one, if your values are positive and you know the smaller one divides the larger one:
def divide(A, B):
return A//B or B//A