Reputation: 89
In this deck shuffling function, nCards represents the number of cards in the deck(52), the for loop gets every number from 1 to 52 a random "j" value by using the ranrange method.
However, I dont understand how "i" could, while increasing throughout the execution of the "for" loop, not end up with "i" being 52 and "j" being 52.
Why? Because that random method gets i between a and b, and as the for loop gets executed, to me, the gap between i and len(nCards)or the range of ncards decreases.
So in my head.
i=1,j=random between 1/52
i=2,j=random between 2/52
i=3,j=random between 3/52
....
i=52,j=random between 52/52
am I wrong? How could I have tested this before posting this here question?
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]
Upvotes: 1
Views: 169
Reputation: 3491
i in range(52)
starts at 0 and counts up to 52. i.e. the last entry is 51. See the docs for reference.
randrange()
chooses an integer from i
to 51, inclusive - i.e. up to 52 (but not 52).
You should probably include random
at the top of the file, not in the method.
If you print i, j
, you will find that the numbers are as expected. For example
0 16
1 24
2 32
...
49 50
50 50
51 51
Upvotes: 2