[prog] python question. Re modulus operator and a few other things.

Jacinta Richardson jarich at perltraining.com.au
Thu Feb 13 16:36:12 EST 2003


> class Deck :
>   def deal(self, hands, nCards=999):
>     nHands = len(hands)
>     for i in range(nCards):
>       if self.isEmpty(): break    # break if out of cards
>       card = self.popCard()       # take the top card
>       hand = hands[i % nHands]    # whose turn is next?
>       hand.addCard(card)          # add the card to the hand

> "The modulus operator (%) allows us to deal cards in a round robin (one card 
> at a time to each hand). When i is equal to the number of hands in the list, 
> the expression i % nHands wraps around to the beginning of the list (index 
> 0). "
> I don't understand how this would work. Wouldn't i % nCards find the 
> remainder of i (which would start at 0 correct?), but that would be 1 / 999 
> and the first 20 rounds would be dealing to the same person...
> how would that work?

note the relevant line says:

hand = hands[i % nHands]    # whose turn is next?


so, if nHands is 4 then:

card # 1:
hand = hands[1 % 4] = 1

card # 2:
hand = hands[2 % 4] = 2

card # 3:
hand = hands[3 % 4] = 3

card # 4:
hand = hands[4 % 4] = 0

card # 5:
hand = hands[5 % 4] = 1

card # 6
hand = hands[6 % 4] = 2

card # 7
hand = hands[7 % 4] = 3

card # 8
hand = hands[8 % 4] = 0


and the cards are dealt round-robin until they run out.

If the line were i % nCards as you read it, then the program would attempt
to deal 1 card to each of 999 hands.  Which would result in dealing to
undefined hands.

Hope this helps.

	Jacinta


--
   ("`-''-/").___..--''"`-._          |  Jacinta Richardson	    |
    `6_ 6  )   `-.  (     ).`-.__.`)  |  Perl Training Australia    |
    (_Y_.)'  ._   )  `._ `. ``-..-'   |      +613 9354 6001 	    |  
  _..`--'_..-_/  /--'_.' ,'           | contact at perltraining.com.au |
(il),-''  (li),'  ((!.-'              |   www.perltraining.com.au   |




More information about the Programming mailing list