1

I'm trying to understand the following code:

import random

SUITS = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
RANKS = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']

def generate_deck(deck):
    for suit in SUITS:
        for rank in RANKS:
            card = [rank+' of '+suit,suit,rank]
            deck += [card]
    return deck

def shuffle(deck):
    n = len(deck)
    for i in range(n):
        r = random.randrange(i, n)
        temp = deck[r]
        deck[r] = deck[i]
        deck[i] = temp
    return deck

The part that I don't really get is:

temp = deck[r]
deck[r] = deck[i]
deck[i] = temp

Does the program take a card, store it in temp and then assigns the new card to the old cards place?

Alessio C.
  • 87
  • 1
  • 1
  • 7
  • 1
    Those three lines are just a way to swap the values of `deck[r]` and `deck[i]`. You can see that as swapping the contents of two glasses. You need a temporary third glass to do the operation. – Guimoute May 25 '20 at 21:33
  • 1
    It swaps the two cards. – matt May 25 '20 at 21:33
  • 1
    Note that in Python that could be replaced by: `deck[r], deck[i] = deck[i], deck[r]` which may be more readable. – norok2 May 25 '20 at 21:34

0 Answers0