[Python-Dev] Retrieve an arbitrary element from a set withoutremoving it

Daniel Stutzbach daniel at stutzbachenterprises.com
Wed Nov 4 00:11:47 CET 2009


On Tue, Nov 3, 2009 at 4:46 PM, Steven D'Aprano <steve at pearwood.info> wrote:

> def pick_two_cards(hand):
>    assert isinstance(hand, (set, frozenset))
>    assert len(hand) == 5
>    return (hand.pick(), hand.pick())
>

Even if pick() chose random, you still might end up picking the same card
twice.  Is that really what you intended?

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.

With the sortedset type, that function would become:

def pick_two_cards(hand):
    assert isinstance(hand, (set, frozenset))
    assert len(hand) == 5
    return random.choice(hand), random.choice(hand)

or if you want to avoid duplicates:

    return random.sample(hand, 2)


Would something like that fit your needs?


[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.

--
Daniel Stutzbach, Ph.D.
President, Stutzbach Enterprises, LLC <http://stutzbachenterprises.com>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20091103/693532ba/attachment.htm>


More information about the Python-Dev mailing list