Beginner Question

Lee Harr missive at frontiernet.net
Thu Mar 27 23:45:04 EST 2003


In article <RcOga.234311$F1.25966 at sccrnsc04>, Kevin Reeder wrote:
> I'm working through the online Python beginner's guide "How to Think Like a
> Computer Scientist" and am stumped on one of the exercises. A
> function to shuffle cards within a class definition called Deck appears
> as follows:
> 
> def shuffle(self):
>     import random
>     nCards = len(self.cards)
>     for i in range(nCards):
>       j = random.randrange(i, nCards)
>       self.cards[i], self.cards[j] = self.cards[j], self.cards[i]
> 
> The problem is to rewrite the last line without using a sequence
> assignment. Everything I've thought of has the result of only inserting
> the random integer j at each index which doesn't solve the problem. I'm
> not really asking for the "right" answer as much as something to jog my
> thought in the right direction!
> 


Well... it is not just the last line, but I think the best way would be:

import random
def shuffle(self):
    random.shuffle(self.cards)



How about this:

def shuffle(self):
    import random
    nCards = len(self.cards)
    for i in range(nCards):
        j = random.randrange(i, nCards)
        self.cards.insert(i, self.cards.pop(j))





More information about the Python-list mailing list