Good way to compare many values/variables?

Attention Topic was automatically imported from the old Question2Answer platform.

Hello,
for my game I need to compare a number of variables to check which one has the highest value.
So far it looks like this:

if A > B and A > C and A > D and A > E:
whatever
elif B > A and B > C and B > D and B > E:
whatever
etc.etc.

And as it could get to an alphabet amount of variables later, that would be quite ugly.
So what would be the best way of checking the highest value for a large number of variables?
I would also be fine if it were all keys in a dictionary,
but then I read it isn’t possible to directly check the highest value in a dictionary either.

Here’s an example of finding the largest value in a dictionary…

var dict = {"a": 10, "b": 5, "c": 22, "d": 55, "e": 27}
var max_var = find_largest_dict_val(dict)
print(max_var)        # prints "d"
print(dict[max_var])  # prints "55"

func find_largest_dict_val(dict):
var max_val = -999999
var max_var
for i in dict:
var val =  dict[i]
if val > max_val:
max_val = val
max_var = i
return max_var

This works perfectly for me. Thanks alot!

Caß | 2020-03-22 00:11

I’m trying to do the opposite if that’s possible…
I want to find the smallest value, not sure how to modify your code to do that…

can you help?

Drewdus42 | 2023-01-11 21:46

Untested, but I think this should work:

var dict = {"a": 10, "b": 5, "c": 22, "d": 55, "e": 27}
var min_var = find_smallest_dict_val(dict)
print(min_var)        # prints "b"
print(dict[min_var])  # prints "5"

func find_smallest_dict_val(dict):
var min_val = 999999
var min_var
for i in dict:
var val =  dict[i]
if val < min_val:
min_val = val
min_var = i
return min_var

jgodfrey | 2023-01-11 21:51

That did work! I thought I tried that already, oh well, thanks so much!

Drewdus42 | 2023-01-11 22:01