The choice of maximum randomness in the case of communication?

From the experiment, I realized that when in the case of a tie, the python selects by order (for example, the element that comes first in the list) Is there a way, when in the case of binding, I can select the element randomly so that it is not deterministic and based on order ?

eg.

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

each run of this can be returned ([4], 10) or ([1], 10) and not always ([1], 10)

+5
source share
3 answers

Shuffle the list before choosing the maximum:

 import random random.shuffle(l) 
+5
source

You will need to first find the maximum max, and then choose one randomly:

 from operator import itemgetter from random import choice l = [([1], 10) , ([2], 3), ([3], 9), ([4], 10)] mx = max(l, key=itemgetter(1)) all_maxes = [ele for ele in l if ele[1] == mx[1]] print(choice(all_maxes)) 
+3
source

You can add a bit of randomness to the key value:

 max(l, key=lambda x: x[1] + random.random()) 

Or in the general case, if your keys are not integers:

 max(l, key=lambda x: (x[1], random.random())) 
+3
source

Source: https://habr.com/ru/post/1234978/


All Articles