Issue 936988: Random.choice doesn't work with sets. (original) (raw)

Created on 2004-04-17 16:20 by jemfinch, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (5)
msg20528 - (view) Author: Jeremy Fincher (jemfinch) Date: 2004-04-17 16:20
Random.sample was changed to work with sets and other non- indexable iterables, but random.choice still requires that its argument be a full sequence. Should that possibly be changed, so that for lists random.choice uses the current implementation, but for other iterables that random.sample supports, it could return random.sample(iterable, 1)[0]?
msg20529 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2004-04-20 19:52
Logged In: YES user_id=80475 I would not like to see that accommodation extended to random.choice(). In random.sample(), it was done to eliminate a surprising assymetry between the two internal algorithms. Because one used list(population) and the other used population.__getitem__(), the first would work with any iterable and the second demanded random access. So, for certain values of n, dictionaries would work find and for other values they would fail. This consideration does not apply to random.choice(). I think most people have a mental model of how it works and would be surprised to have an iterable input fully manitested in memory. Though, I do grant that it is also surprising that it does not work with sets. C'est le vie.
msg20530 - (view) Author: Jeremy Fincher (jemfinch) Date: 2004-04-20 23:26
Logged In: YES user_id=99508 An iterable input does not have to be fully manifested in memory for random.choice to work. See the implementation at <http://www.pastebin.de/pastebin.py? id=594>. Is this to say that random.sample entirely manifests large iterables in memory? I would say that this would be just as unexpected as random.choice doing so. If it's not the case, then why can't random.choice do what it does now for proper sequences, but just dispatch to random.sample(iterable, 1)[0] in all other cases?
msg20531 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2004-04-21 01:23
Logged In: YES user_id=80475 Sorry, I don't think this is a good idea and do not want to introduce O(n) behavior into an otherwise O(1) function.
msg20532 - (view) Author: Tim Peters (tim.peters) * (Python committer) Date: 2004-04-21 01:39
Logged In: YES user_id=31435 I agree with Raymond on this -- making random.choice() an O (n) function in some cases would make it an attractive nuisance. In the absence of an efficient implementation, it's regrettable that random.sample() decided to cater to sets. Doing more damage of the same kind would primarily be doing more damage.
History
Date User Action Args
2022-04-11 14:56:03 admin set github: 40164
2004-04-17 16:20:31 jemfinch create