I'm trying to use random numbers to access an item in a list, and then once that item has been called it should not be called again. ex: list = [1,2,3,4,5] - I want to be able to pull out each item at random until all have been pulled - without any repeating.
below is the actual code in which I tried - and failed - to implement this.
from random import *
def make_hand():
cards = ["AC", "AS", "AD", "AH", "2C", "2S", "2D", "2H", "3C", "3S", "3D", "3H", "4C", "4S", "4D", "4H", "5C",
"5S", "5D", "5H", "6C", "6S", "6D", "6H", "7C", "7S", "7D", "7H", "8C", "8S", "8D", "8H", "9C", "9S",
"9D", "9H", "10C", "10S", "10D", "10H", "JC", "JS", "JD", "JH", "QC", "QS", "QD", "QH", "KC", "KS", "KD",
"KH"] # list of all cards in a deck. c = clubs, s = spades, d = diamonds, h = hearts
used_cards = [] # list to check that no card is ever used twice.
rn = randint(0, 51) # method of picking a random card
used_cards.append(rn) # adds picked card to list of used cards
rn2 = randint(0, 51)
while rn2 in used_cards: # checks if card has been used, and if so changes value
rn2 = randint(0, 51)
used_cards.append(rn2)
rn3 = randint(0, 51)
while rn3 in used_cards:
rn3 = randint(0, 51)
used_cards.append(rn3)
rn4 = randint(0, 51)
while rn4 in used_cards:
rn4 = randint(0, 51)
used_cards.append(rn4)
rn5 = randint(0, 51)
while rn5 in used_cards:
rn5 = randint(0, 51)
used_cards.append(rn5)
return cards[rn], cards[rn2], cards[rn3], cards[rn4], cards[rn5]
def test_make_hand():
num = 50
while num > 0:
assert make_hand()[0] != make_hand()[1] != make_hand()[2] != make_hand()[3] != make_hand()[4]
num -= 1
return True
EDIT: after all the feed back from you guys it's much prettier and more functional now!
from random import *
cards = ["AC", "AS", "AD", "AH", "2C", "2S", "2D", "2H", "3C", "3S", "3D", "3H", "4C", "4S", "4D", "4H", "5C",
"5S", "5D", "5H", "6C", "6S", "6D", "6H", "7C", "7S", "7D", "7H", "8C", "8S", "8D", "8H", "9C", "9S",
"9D", "9H", "10C", "10S", "10D", "10H", "JC", "JS", "JD", "JH", "QC", "QS", "QD", "QH", "KC", "KS", "KD",
"KH"] # list of all cards in a deck. c = clubs, s = spades, d = diamonds, h = hearts
def make_hand(num):
while num > 0:
shuffle(cards)
hand = [cards[x] for x in range(5)]
for x in hand:
if x in cards:
cards.remove(x)
print(len(cards))
print(hand)
num -= 1