[Tutor] Use functions re avoid Re: Can the following algorithm be improved?

Roel Schroeven rschroev_nospam_ml at fastmail.fm
Tue Aug 9 14:39:55 CEST 2005

Brian van den Broek wrote:

> Say you go with your method of defining a deck (cards above) and then 
> making random choices from it. Try something like this (untested code):
> cards = ["Ace of ...",] # As above
> cards_dealt = []
> def get_card():
>      while True:
>          new_card = random.choice(cards)]
>          if new_card not in cards_dealt:
>              cards_dealt.append(new_card)
>              break
>      return new_card

The random module has a nice function for this:

sample( population, k)

Return a k length list of unique elements chosen from the population 
sequence. Used for random sampling without replacement. New in version 2.3.
Returns a new list containing elements from the population while leaving 
the original population unchanged. The resulting list is in selection 
order so that all sub-slices will also be valid random samples. This 
allows raffle winners (the sample) to be partitioned into grand prize 
and second place winners (the subslices).

Members of the population need not be hashable or unique. If the 
population contains repeats, then each occurrence is a possible 
selection in the sample.

To choose a sample from a range of integers, use xrange as an argument. 
This is especially fast and space efficient for sampling from a large 
population: sample(xrange(10000000), 60).

If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

Roel Schroeven

More information about the Tutor mailing list