How to compare a variable with a set (to see if there are duplicates) and if there are, How do i remove them and repeat the process?

Question:

I’m new here, so I’m sorry if this isn’t a good way of asking a question…

This is my code:

import random
i = 0
#the numbers of the cards
numbers = ["A","2","3","4","5","6","7","8","9","10","Jack","Queen","King"]
#the suits of decks
suits = ["Spades","Hearts","Clubs","Diamonds"]
#empty list
used = []
#Generate random Number and Suit
while i != 5:
    number = random.choice(numbers)
    suit = random.choice(suits)
    print (number+" of "+suit)
    used.append(number + " of " + suit)
    i += 1

What I am trying to achieve is to have the code generate a series of 5 cards without duplicates and then printing those…

But I don’t know how to get rid of the duplicates and then continue the code…

What I am currently getting is this:

King of Spades
King of Spades
Queen of Hearts
A of Clubs
6 of Hearts
['King of Spades', 'King of Spades', 'Queen of Hearts', 'A of Clubs', '6 of Hearts']

Thanks in advance!

EDIT: Can’t take my typos and bad capitalizations any more. I have to change them…

Asked By: s11010

||

Answers:

Try this:

import itertools
import random
numbers = ["A","2","3","4","5","6","7","8","9","10","Jack","Queen","King"]
#the suits of decks 
suits = ["Spades","Hearts","Clubs","Diamonds"]
deck=list(itertools.product(numbers,suits))
random.shuffle(deck)
for i in range(5):
    print( deck[i][0],'of' ,deck[i][1])
Answered By: Shadowcoder

To get rid of duplicating cards, try adding the line as follows:

# Generate random Number and Suit
while i != 5:
    number = random.choice(numbers)
    numbers.remove(number) ###
    suit = random.choice(suits)
    print(number + " of " + suit)
    used.append(number + " of " + suit)
    i += 1
Answered By: Code4

There is also the solution of using for loops…

import random as r

numbers = ["Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"]
suits = ["Spades","Hearts","Clubs","Diamonds"]

deck = [number + " of " + suit for suit in suits for number in numbers]
r.shuffle(deck)

for i in range(5):
    print(deck[i])
Answered By: s11010
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.