Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out which variable has the greatest value

Tags:

python

if A > B and C and D:
   print("A wins")
if B>A and C and D:
   print("B wins")

How do I check and see which variable contains the largest integer out of the group? Deciding who wins?

like image 726
user3548949 Avatar asked Mar 19 '23 20:03

user3548949


1 Answers

You could test each one:

if A > B and A > C and A > D:

or you could just test against the maximum value of the other three:

if A > max(B, C, D):

but it appears what you really want is to figure out which player has the maximum value. You should store your player scores in a dictionary instead:

players = {'A': A, 'B': B, 'C': C, 'D': D}

Now it is much easier to find out who wins:

winner = max(players, key=players.get)
print(winner, 'wins')

This returns the key from players for which the value is the maximum. You could use players throughout your code rather than have separate variables everywhere.

To make it explicit: A > B and C and D won't ever work; boolean logic doesn't work like that; each expression is tested in isolation, so you get A > B must be true, and C must be true and D must be true. Values in Python are considered true if they are not an empty container, and not numeric 0; if these are all integer scores, C and D are true if they are not equal to 0.

like image 109
Martijn Pieters Avatar answered Mar 22 '23 09:03

Martijn Pieters