I was curious: how does Python implement random.choice() from a set ?
I can imagine a very slow solution : choose a number n between 1 and len(set) and then iterate n times and return the item.
I was curious: how does Python implement random.choice() from a set ?
I can imagine a very slow solution : choose a number n between 1 and len(set) and then iterate n times and return the item.
random.choice()
does not actually support sets:
>>> import random
>>> s = {1, 2, 3, 4, 5}
>>> random.choice(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python3.4/random.py", line 256, in choice
return seq[i]
TypeError: 'set' object does not support indexing
You can, however, convert the set to a list:
>>> random.choice(list(s))
2
Sets do not support object indexing. So you need to convert. Using a tuple instead of a list is more efficient for instantiation:
s = set([1, 2, 3, 4, 5, 6])
print random.choice(tuple(s))
If you are looking for clarity, an alternative choice is to use sample. However, it is not very efficient as internally as the first example it does convert anyway.
s = set([1, 2, 3, 4, 5, 6])
print random.sample(s, 1)