Welcome, guest | Sign In | My Account | Store | Cart

Python function to shuffle a deck of cards

Python, 21 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import random
import unittest

def shuffle(cards):
    max = len(cards)-1
    while max != 0:
        r = random.randint(0, max)
        cards[r], cards[max] = cards[max], cards[r]
        max = max - 1
    return cards

class TestCase(unittest.TestCase):
    def setUp(self):
        self.actual = range(1, 53)

    def test_elements(self):
        expected = shuffle(self.actual)
        self.assertEqual(set(self.actual), set(expected))

if __name__ == "__main__":
    unittest.main()

3 comments

beni hess 11 years, 2 months ago  # | flag
Thomas Woelz 11 years, 1 month ago  # | flag

careful, max is a Python built-in function (returns the higher value from a list)

Yuanming 11 years, 1 month ago  # | flag

random.shuffle(cards) or random.sample(cards, len(cards)) would do the same things