This still seems wrong *unless* we add a protocol to select a random
item in O(1) time. There currently isn't one for sets and mappings --
only for sequences. It would be pretty terrible if someone wrote code
to get N items from a set of size N and their code ended up being
O(N**2).
On Tue, Apr 12, 2016 at 3:57 PM, Ben Finney
Rob Cliffe
writes: It surprised me a bit the first time I realised that random.choice did not work on a set. (One expects "everything" to "just work" in Python! :-) )
I am +1 on the notion that an instance of ‘tuple’, ‘list’, ‘set’, and even ‘dict’, should each be accepted as input for ‘random.choice’.
On 2011-06-23, Sven Marnach posted 'A few suggestions for the random module' on Python-Ideas, one of which was to allow random.choice to work on an arbitrary iterable.
I am −1 on the notion of an arbitrary iterable as ‘random.choice’ input.
Arbitrary iterables may be consumed merely by being iterated. This will force the caller to make a copy, which may as well be a normal sequence type, defeating the purpose of accepting that “arbitrary iterable” type.
Arbitrary iterables may never finish iterating. This means the call to ‘random.choice’ would sometimes never return.
The ‘random.choice’ function should IMO not be responsible for dealing with those cases.
Instead, a more moderate proposal would be to have ‘random.choice’ accept an arbitrary container.
If the object implements the container protocol (by which I think I mean that it conforms to ‘collections.abc.Container’), it is safe to iterate and to treat its items as a collection from which to choose a random item.
Rob, does that proposal satisfy the requirements that motivated this?
-- \ “Some people, when confronted with a problem, think ‘I know, | `\ I'll use regular expressions’. Now they have two problems.” | _o__) —Jamie Zawinski, in alt.religion.emacs | Ben Finney
_______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/
-- --Guido van Rossum (python.org/~guido)