如何防止Python中两个不同变量生成两个相同的随机数?

时间:2017-10-27 00:55:16

标签: python variables random

我在下面发布了我的代码,我被卡在了assignCard(person)功能上。我想打印10个随机数;变量x为5,变量y为5。如何防止x等于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()

1 个答案:

答案 0 :(得分:0)

这应该适合你:

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()

它将继续重新分配y,直到xy不相等。