user3548949
user3548949

Reputation: 43

How to find out which variable has the greatest value

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?

Upvotes: 4

Views: 21809

Answers (2)

Thom Wiggers
Thom Wiggers

Reputation: 7044

You could use max():

if A > max(B,C,D):
    print("A wins")
elif B > max(A,C,D):
    print("B wins")

Of course there's also a functional programming way to do this:

var_names = ['A', 'B', 'C', 'D']
max_var = max(zip(names, (map(eval, var_names))), key=lambda tuple: tuple[1])[0]
print("%s wins!" % max_var)

The zip and map transforms the var_names list into a list of tuples like ('A', A), then it gets the tuple with the highest second item. From that tuple it grabs the variable name.

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121844

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.

Upvotes: 8

Related Questions