I have two lists compared for a game to see if one is greater/less or if they are equal.
If I use <=
or >=
the boolean value will print a win/lose. But if they are equal, the value will still be either win/lose. Is there a way to print "tie" without a bunch of if
statements?
What I have now is this:
totalA = [5, 5, 5]
totalB = [5, 5, 5]
grandtotal = sum(totalA) <= sum(totalB)
if grandtotal == True:
print("Win")
else:
print("Lose")
If you have three possible outcomes, that's not a boolean value, since a boolean value by definition only has two possibilities. Capturing three possibilities with booleans requires at least two booleans (eg "Win" if a < b else "Lose" if b < a else "Tie"
). But if you want to do it with no if
statements at all, there's a way!
Create a mathematical comparison function that'll return a result from the set -1, 0, 1
based on which of the two numbers is bigger, and then map those results to the desired strings.
print({
1: "Win",
0: "Tie",
-1: "Lose",
}[(sum(totalB) - sum(totalA)) // (abs(sum(totalB) - sum(totalA)) or 1)])
Putting it into a function (and adding a bit of int
conversion to make it handle float
inputs as well):
>>> def print_result(totalA, totalB):
... delta = sum(totalB) - sum(totalA)
... print({
... 1: "Win",
... 0: "Tie",
... -1: "Lose",
... }[int(delta // (abs(delta) or 1))])
...
>>> print_result([5, 5, 5], [5, 5, 5])
Tie
>>> print_result([1, 2, 3], [2, 3, 4])
Win
>>> print_result([3, 4, 5], [2, 3, 4])
Lose
>>> print_result([5, 5, 5], [5, 5, 5.0])
Tie
>>> print_result([5, 5.1, 5], [5, 5, 5.0])
Lose
>>> print_result([5, 5.1, 5], [5, 5.2, 5.0])
Win
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.