Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choosing a maximum randomly in the case of a tie?

From experiment I have relised that when in a case of a tie, python picks based on order (e.g. the item that comes in first in a list) Is there a way, where in the case of a tie i can choose an item randomly, so that it is not deterministic and based on order?

e.g.

l = [ ([1], 10) , ([2], 3), ([3], 9), ([4], 10)] 
max(l, key=lambda x: x[1])

each run of this, could either return ([4], 10) or ([1], 10) and not always ([1], 10)

like image 794
user Avatar asked Nov 01 '15 23:11

user


People also ask

What does Max do in a tie Python?

Python max() function The max() function returns the largest of the input values. An iterable object like string, list, tuple etc.

Can Max return multiple values Python?

Passing Two or More Values to the Python max() MethodWhen two or more values are passed to the max() method, it returns the maximum or largest of them all. These arguments can be integers, floating-point values, characters or even strings. As desired, we get the maximum value, 73.

How do you find the max in Python?

Use max() to Find Max Value in a List of Strings and Dictionaries. The function max() also provides support for a list of strings and dictionary data types in Python. The function max() will return the largest element, ordered by alphabet, for a list of strings. The letter Z is the largest value, and A is the smallest.


1 Answers

Shuffle the list before picking the maximum:

import random
random.shuffle(l)
like image 92
Karoly Horvath Avatar answered Sep 30 '22 06:09

Karoly Horvath