0

[SOLVED] How does the random.choices function work in Python?

And in which ways does it differ with random.sample and random.choice?

20th Jan 2019, 10:45 AM
giannismach
giannismach - avatar
5 Answers
+ 7
random.choices(list, weights=list, cum_weights=list, k=int) returns k elements from list with weighted probabilites. Example: from random import choices dice = [*range(1, 7)] # [1, 2, 3, 4, 5, 6] weights = [1 for i in range(6)] # [1, 1, 1, 1, 1, 1], equal weights => same probability for every number print(choices(dice, weights=weights, k=10)) # [2, 2, 3, 2, 4, 4, 5, 6, 4, 3] weights = [0, 0, 0, 1, 1, 5] # first three elements have a weight of 0 and will be excluded. 6 has the heighest weight/probability print(choices(dice, weights=weights, k=10)) # [6, 5, 6, 5, 5, 6, 6, 4, 6, 6] cum_weights means that the probablities are added up instead of listed individually: weights = [1, 1, 1, 1, 1, 1] # cumulated weights don't change = there's a 100% chance for a 1 print(choices(dice, cum_weights=weights, k=10)) # [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
20th Jan 2019, 11:05 AM
Anna
Anna - avatar
+ 4
random.choice() selects a random object from the list. >>> random.choice([1,2,3,4]) 2 random.sample() allows you to randomly select more than 1 object, and return them as a list. >>> random.sample([1,2,3,4], 2) [1,3]
20th Jan 2019, 10:50 AM
Hatsy Rei
Hatsy Rei - avatar
+ 4
Guess I'm really blind. Sorry about that. :D Anyway, I'm sure you've also read the docs? https://docs.python.org/3/library/random.html According to what is defined, it appears that random.choices work like random.sample but allows you to specify weights to each element.
20th Jan 2019, 11:06 AM
Hatsy Rei
Hatsy Rei - avatar
+ 3
Anna Thank you very much! Thank you too, Hatsy Rei!
20th Jan 2019, 11:10 AM
giannismach
giannismach - avatar
0
Hatsy Rei thanks, but in fact I already knew about these two. My question is about the random.choices() function and its differences with random.sample() and random.choice().
20th Jan 2019, 10:53 AM
giannismach
giannismach - avatar