0

Here's some code for shuffling a deck of cards manually. I understand it up to the point where cards[pos], cards[randpos] = cards[randpos], cards[pos]. What is happening here? What is the point of assigning cards[pos] to cards[randpos]?

self.cards is a list of playing cards in standard order.

  def shuffle(self):
        n = len(self.cards)
        cards = self.cards
        for pos in range(n):
            randpos = randrange(pos,n)
            cards[pos], cards[randpos] = cards[randpos], cards[pos]

6 Answers6

3

The values of cards[pos] and cards[randpos] are being switched. This is a common Python idiom: you can switch two or more variables' values by saying a, b = b, a.

Note that the standard library implementation of shuffling (random.shuffle()) is quite similar.

Rafe Kettler
  • 75,757
  • 21
  • 156
  • 151
  • “quite similar” but [very different](http://www.codinghorror.com/blog/2007/12/the-danger-of-naivete.html) in “randomness”. The Python library function results in better “randomness”. – tzot Mar 14 '11 at 21:06
  • @ΤΖΩΤΖΙΟΥ Correct. It was my way of saying "use the standard library, they already do it for you". Btw, your name is quite difficult to type... – Rafe Kettler Mar 14 '11 at 21:13
1

It's swapping the positions of the cards in pos and randpos.

So, for example, if your list were [1,2,3,4,5,6,7] and pos were 0, first it would pick an index that comes after the 1 in the list. Then it would swap the 1 and the number at that index. So if randpos is 3 on the first iteration, we end up with [4,2,3,1,5,6,7] after one time through the loop.

As a side note, it is much more efficient (and reliable) to use random.shuffle().

nmichaels
  • 49,466
  • 12
  • 107
  • 135
1

In python

a, b = b, a

is how you swap two variables. In your code what are swapped are the contents of the list at position pos and randpos.

6502
  • 112,025
  • 15
  • 165
  • 265
1
cards[pos], cards[randpos] = cards[randpos], cards[pos]

This is simply swapping cards[pos] and cards[randpos]

Here's an entire Web page on the technique: http://blog.mithis.net/archives/ideas/64-python-swap-var

payne
  • 13,833
  • 5
  • 42
  • 49
1

cards[pos], cards[randpos] = cards[randpos], cards[pos]

Is swapping the card at index pos with the card at index randpos

It's basically assigning card[randpos] to card[pos] and card[pos] to card[randpos]. Another way to do it would be

t = card[pos]
card[pos] = card[randpos]
card[randpos] = t

The former is just shorter and more pythonic.

GWW
  • 43,129
  • 11
  • 115
  • 108
0

It's basically randomly swapping cards. It's taking cards[pos] out of the deck, placing cards[randpos] at its location, and placing cards[pos] back at where cards[randpos] was.

Also note, that Python provides random.shuffle so that you don't have to do this manually.

user470379
  • 4,879
  • 16
  • 21