A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from http://mail.python.org/pipermail/python-dev/2009-November/093681.html below:

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

[Python-Dev] Retrieve an arbitrary element from a set withoutremoving itDaniel 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

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4