Matteo
Matteo

Reputation: 35

How do I prevent two of the same random numbers being generated from two different variables in Python?

I have posted my code below, I am stuck on the assignCard(person) function. I want to print out 10 random numbers; 5 for the variable x and 5 for the variable y. How can I prevent x from equaling y?

""" cardGame.py
    basic card game framework
    keeps track of card locations for as many hands as needed
"""
from random import *
import random

NUMCARDS = 52
DECK = 0
PLAYER = 1
COMP = 2

cardLoc = [0] * NUMCARDS
suitName = ("hearts", "diamonds", "spades", "clubs")
rankName = ("Ace", "Two", "Three", "Four", "Five", "Six", "Seven", 
            "Eight", "Nine", "Ten", "Jack", "Queen", "King")
playerName = ("deck", "player", "computer")

def main():
  clearDeck()

  for i in range(5):
    assignCard(PLAYER)
    assignCard(COMP)

  print(cardLoc)

  #showDeck()
  #showHand(PLAYER)
  #showHand(COMP)

def clearDeck():
    cardLoc = [0] * NUMCARDS

def assignCard(person):
  x = random.randint(0, 53)
  y = random.randint(0, 53)
  if person == PLAYER:
    cardLoc[x] = 1
  elif person == COMP:
    cardLoc[y] = 2
main()

Upvotes: 0

Views: 662

Answers (1)

gommb
gommb

Reputation: 1117

This should work for you:

def assignCard(person):
  x = random.randint(0, 53)
  while True:
      y = random.randint(0, 53)
      if x != y:
          break
  if person == PLAYER:
    cardLoc[x] = 1
  elif person == COMP:
    cardLoc[y] = 2
main()

It will keep reassigning y until x and y aren't equal.

Upvotes: 1

Related Questions