[Tutor] Debugging While Loops for Control
Robert Sjoblom
robert.sjoblom at gmail.com
Fri Feb 17 18:51:49 CET 2012
>> class Card(object):
>> def __init__(self):
>> self.score = self.deal()
>>
>> def deal(self):
>> """deal a card from 1 to 52 and return it's points"""
>> return self.getValue(int(math.floor(random.uniform(1,
>> 52))))
>
> I think you only need random.randint(1,52) here. It simplifies it quite a
> lot! But you still have the problem that you might wind up with two
> identical cards! It might be better to create a deck(list) of 52 cards,
> shuffle() them and then pop the value off of that deck.
I'd suggest using random.sample() instead, but it might just be a
matter of style:
>>> from random import sample
>>> deck = range(1,53)
>>> sample(deck, 2)
[43, 9]
>>> sample(deck, 2)
[8, 27]
It's a function a lot of people doesn't know about, for some reason.
Best part is that it leaves deck (or whatever population you're taking
the sample from) alone, so you don't have to rebuild it every time you
want to reset the deck. Ah, but I suppose you want to keep track of
what cards are available, too. Forgot about that part. I guess you can
do:
sample(deck, 52) #or instead of deck range(1,53)
for each new round, and pop items from the returned sample instead of
popping the deck list every time. In the end I suppose it's a matter
of style. Oh, and the returned list is in selection order (which might
be important but maybe not in Black Jack). Maybe I should have just
stayed quiet.
--
best regards,
Robert S.
More information about the Tutor
mailing list