[ python-Bugs-1551113 ] random.choice(setinstance) fails

SourceForge.net noreply at sourceforge.net
Sat Sep 2 20:27:30 CEST 2006


Bugs item #1551113, was opened at 2006-09-02 13:27
Message generated for change (Tracker Item Submitted) made by Item Submitter
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1551113&group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Python Library
Group: None
Status: Open
Resolution: None
Priority: 5
Submitted By: Alan (aisaac0)
Assigned to: Nobody/Anonymous (nobody)
Summary: random.choice(setinstance) fails

Initial Comment:
It seems perverse that random.choice cannot pick from 
a set.
(Maybe it is also perverse that it cannot pick a key 
from a dict.)
The current definition is

def choice(self, seq):
    """Choose a random element from a non-empty 
sequence."""
    return seq[int(self.random() * len(seq))]  # 
raises IndexError if seq is empty

How about something along the lines of:

def choice(self, seq):
    """Choose a random element from a non-empty 
sequence."""
    idx = int(self.random() * len(seq))
    try:
        result = seq[idx]  # raises IndexError if seq 
is empty
    except TypeError:
        result = list(seq)[idx]
    return result
 


----------------------------------------------------------------------

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1551113&group_id=5470


More information about the Python-bugs-list mailing list