Yakov
0
Q:

python randomly sample entry from a set

import random
cakes = ['lemon', 'strawberry', 'chocolate']
random.choice(cakes)
# prints 1 randomly selected item from the collection of n items with 
# the probability of selection as 1/n
4
import random

# with replacement = same item CAN be chosen more than once.
# without replacement = same item CANNOT be chosen more then once.

# Randomly select 2 elements from set without replacement and return a list
random.sample(set_name, 2)
1
# Basic syntax:
import random
random.sample(your_set, number_of_elements)
# Where:
#	- number_of_elements is the number of elements you want to sample
# 		without replacement from your_set
# Note, the samples elements are returned as a list. Use set(the_list)
#	to convert back to a set

# Example usage:
your_set = {'a', 'bunch', 'of', 'unique', 'words'}
random.sample(your_set, 1)
--> ['words']

random.sample(your_set, 3)
--> ['words', 'of', 'a']
1

New to Communities?

Join the community