[Python-ideas] random.choice on non-sequence

Chris Angelico rosuav at gmail.com
Wed Apr 13 06:46:08 EDT 2016


On Wed, Apr 13, 2016 at 8:36 PM, Terry Reedy <tjreedy at udel.edu> wrote:
> On 4/13/2016 12:52 AM, Chris Barker - NOAA Federal wrote:
>
>> BTW, isn't it impossible to randomly select from an infinite iterable
>> anyway?
>
>
> With equal probability, yes, impossible.
> With skewed probabilities, no, possible.

What, you mean like this?

def choice(it):
    it = iter(it)
    value = next(it)
    try:
        while random.randrange(2):
            value = next(it)
    except StopIteration: pass
    return value

I'm not sure how useful it is, but it does accept potentially infinite
iterables, and does return values selected at random...

ChrisA


More information about the Python-ideas mailing list