Python function to shuffle a deck of cards
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()
|
Tags: shuffle
Why not random.shuffle? http://docs.python.org/2/library/random.html#random.shuffle
careful, max is a Python built-in function (returns the higher value from a list)
random.shuffle(cards) or random.sample(cards, len(cards)) would do the same things