Beginner Question
Alex Martelli
aleax at aleax.it
Fri Mar 28 06:08:01 EST 2003
Kevin Reeder wrote:
> On Thu, 27 Mar 2003 20:45:04 -0800, Lee Harr wrote:
>
>> 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)
>
> This one failed to work with the exception: Attribute error: shuffle.
> Probably something I'm not seeing.
Weird. Can you please try to reproduce the error "in the small" and
just copy and paste it to a post rather than summarizing it? For me
it works just fine, e.g.:
>>> import random
>>> def shuffle(self):
... random.shuffle(self.cards)
...
>>> class X:
... cards = list('pacilokeruny')
...
>>> shuffle(X)
>>> X.cards
['u', 'k', 'r', 'y', 'a', 'e', 'c', 'o', 'l', 'p', 'i', 'n']
>>>
What happens when YOU try this exact code? If this works and your
script doesn't, what's the essential difference that breaks your
script?
>> 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))
>
> This solution worked great. Is insert a list method?
Yes, it is. But in your shoes I'd invest more effort in trying
to make random.shuffle work -- it's going to be faster (with Tim
Peters having programmed it, that's almost guaranteed;-) AND
you're going to feel more secure in its correctness (ditto) -- this
one does seem OK, but inspection might miss some subtle issue...
using solid modules from the standard library is just safer!-)
Alex
More information about the Python-list
mailing list