Wednesday 25 September 2013 — This is 11 years old. Be careful.
I’m an organizer for Boston Python, and we like to raffle off books at events. I’ve got a technique I like for doing it. Here it is recorded for posterity.
We use meetup.com to handle RSVPs for events. I have a small program that queries the meetup.com API for people who have RSVP’d “yes” to an event. I use it to get a list of names, then I shuffle the names, make an iterator, then pick names off it. I do this on the big screen in an interactive prompt:
>>> import random
>>> from attendees import yes
>>> people = yes(120746442) # The event number from meetup.com
>>> len(people)
174
>>> random.shuffle(people) # Give them a good shake
>>> pick = iter(people) # Make an iterator
>>> print next(pick) # Now pick people!
Ned Batchelder
>>> print next(pick)
Jessica McKellar
>>> print next(pick)
Jason Michalski
>>> # etc...
>>>
Iterables like the list of people’s names are usually iterated completely with a for loop or a list comprehension. But you can step them one item at a time if you like. iter() creates an iterator from an iterable (confusing, I know...), then you can use next() to get the next item from the iterable.
There aren’t many reasons to use iterators like this, but occasionally it can be useful.
Comments
1) Random.sample isn't as good for picking people, since the second sample could pick the same person again. Not a big deal, easily dealt with.
2) I like that this technique shows off a little-traveled area of Python knowledge.
3) For the same reason that random.shuffle can't produce all possible permutations, neither can repeated calls to random.sample: the set of all possible permutations or sampling sequences is larger that the set of all possible random generator states. So using sample won't fix the problem. Luckily, it isn't much of a problem, since we're only going to pick a handful of names anyway.
Add a comment: