shuffling elements of a list

John Machin sjmachin at lexicon.net
Wed May 31 00:40:00 EDT 2006


On 31/05/2006 1:18 PM, greenflame wrote:
> I would like to make a function that takes a list, more specificaly a
> list of strings, and shuffles its elements, like a pile of cards. The
> following is a script I tryed to make that implements pile shuffling.
> 

In general, if you can't see why Python is complaining, insert print 
statements.

Anyhow, read the following, run it, read it again, ...

HTH,
John


def pileshuffle1(deck, numpiles, fix1bug=False):
     piles = [[]] * numpiles
     # 2nd bug: n references to *same* sublist
     card = 0
     pilenum = 0
     while card < len(deck):
         print card, pilenum
         assert 0 <= pilenum < numpiles
         piles[pilenum].append(deck[card])
         card += 1
         if not fix1bug:
             if pilenum < numpiles:
                 pilenum += 1
             else:
                 pilenum = 0
         else:
             pilenum = (pilenum + 1) % numpiles
     print
     print piles

def pileshuffle2(deck, numpiles):
     piles = [[] for x in range(numpiles)] # n *different* sublists
     for cardindex, card in enumerate(deck):
         piles[cardindex % numpiles].append(card)
     print
     print piles

pileshuffle1('qwertyuiop', 3, True)
pileshuffle2('qwertyuiop', 3)
pileshuffle1('qwertyuiop', 3, False)



More information about the Python-list mailing list