<div class="gmail_quote">On Tue, Nov 3, 2009 at 4:46 PM, Steven D'Aprano <span dir="ltr"><<a href="mailto:steve@pearwood.info">steve@pearwood.info</a>></span> wrote:<br><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
def pick_two_cards(hand):<br>
assert isinstance(hand, (set, frozenset))<br>
assert len(hand) == 5<br>
return (hand.pick(), hand.pick())<br></blockquote><div><br>Even if pick() chose random, you still might end up picking the same card twice. Is that really what you intended?<br></div></div><br>FWIW, I've been working on an extension module that supplies a "sortedset" type [1]. In most ways, it's similar to a set except it's indexable like a list. The items are kept in sorted order, so index 0 is always the lowest item, index 1 is the next-to-lowest, etc. Because they're indexable, it's easy and efficient to retrieve random elements using the standard library's "random" module.<br>
<br>With the sortedset type, that function would become:<br><br>def pick_two_cards(hand):<br>
assert isinstance(hand, (set, frozenset))<br> assert len(hand) == 5<br> return random.choice(hand), random.choice(hand)<br><br>or if you want to avoid duplicates:<br><br> return random.sample(hand, 2) <br><br>
<br>Would something like that fit your needs?<br><br><br>[1] It's already implemented, along with sortedlist, weaksortedlist, and weaksortedset types. I'm just putting them through the paces in my own products before releasing them.<br>
<blockquote style="margin: 1.5em 0pt;">--<br>
Daniel Stutzbach, Ph.D.<br>
President, <a href="http://stutzbachenterprises.com">Stutzbach Enterprises, LLC</a>
</blockquote>