How to prevent receiving the same random data from the list in python

Viewed 59

I want to check that the random cards from the list are not the same card. How can I do that? Can you help me? Thanks.

import random
vals = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
suits = ['C', 'D', 'H', 'S']
name = []
playercount=int(input("Please Enter Number of Player = "))

if  2 <= playercount <= 5:
    for i in range(playercount):
        username=str(input("Please Enter Player Name: "))
        if not username:
            name.append("Player {}".format(i+1))
            name.append(random.choices(vals))
            name.append(random.choices(suits))    
        else:   
            name.append(username)
            name.append(random.choices(vals))
            name.append(random.choices(suits))
    print("Players, Vals and Suits on the Desk ")
    for x in range(len(name)):
        print (name[x])
else:
    print("Try Again")
1 Answers

One strategy would be to create a list that stores the cards in a deck and to randomly draw cards from that list. Each time a card is drawn, that card is removed from that list so that when you draw more cards randomly from that list, you never get the same card more than once.

not_in_hand = [x + y for x in vals for y in suits]

In a program, this might look like

import random

rank = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
suit = ['C', 'D', 'H', 'S']

# list of all possible cards
not_in_hand = [x + y for x in rank for y in suit]

# dictionary whereby a key is a player name (e.g. 'Bonnie') and a value is
# a card (e.g. '2C')
hands = {}

while True:
    try:
        playercount = int(input("Number of Players: "))
    except ValueError:
        print("Please enter an integer in [2,5]!")
        continue

    if 2 <= playercount <= 5:
        break
    else:
        print("Player count must be in [2, 5].")


for i in range(playercount):
    username = input("Enter Player Name: ")
    # if nothing entered, give default name
    if not username:
        username = f"Player {i + 1}"

    # randomly draw a card
    index = random.randint(0, len(not_in_hand) - 1)
    card = not_in_hand.pop(index)

    # record the card that the player has drawn
    hands[username] = card

print(hands)

Output:

Number of Players: jack
Please enter an integer in [2,5]!
Number of Players: 1
Player count must be in [2, 5].
Number of Players: 3
Enter Player Name: Bonnie
Enter Player Name: Clyde
Enter Player Name: 
{'Bonnie': 'AH', 'Clyde': 'KD', 'Player 3': '7S'}

I hope that this helps. Please let me know if there are any questions.

Related