gpt4 book ai didi

python - python 中 while 循环中 randrange() 的空范围

转载 作者:行者123 更新时间:2023-12-01 01:28:21 25 4
gpt4 key购买 nike

在经过 while 循环后,我在从函数中获取随机 int 时遇到了问题。该函数的目的是洗牌:

def shuffling(maindeck, shuffle_steps):
random.seed()
# sets a number of steps and creates a new array to be returned
steps = 0
shuffler = maindeck

while steps < shuffle_steps:
firstR = random.randrange(len(maindeck) - 1)
secondR = random.randrange(len(maindeck) - 1)

shuffler[firstR], shuffler[secondR] = shuffler[secondR], shuffler[firstR]

steps +=1

return shuffler

这是使用该函数的代码:

from deck import *
from shuffle import shuffling
gameState = True


while gameState:
input("Welcome to War! Press any key to continue... \n")

game_deck = shuffling(total_deck, 500)

while gameState and len(game_deck) > 1:
print("Both players draw a card...")

playerCard = game_deck.pop(0)
opponentCard = game_deck.pop(0)

# some code

keep_playing = input("Play again? (y/n) \n")
if keep_playing is not ('y' or 'Y'):
gameState = False

gameState = False

if len(game_deck) < 2:
print("No cards left!")
keepPlaying = input("Play again? (y/n) \n")
if keepPlaying is ('y' or 'Y'):
gameState = True

其中total_deck是来自文件deck.py的数组

这段代码在 while 循环的第一次迭代中工作正常,但是当循环迭代时我收到错误:

 ValueError: empty range for randrange()

并且错误发生在

random.randrange(len(Maindeck) - 1) 

被调用,因为

len(Maindeck) - 1 

现在计算结果为等于或小于 0 的数字?为什么是这样?

最佳答案

选项:

  • 如果您的列表中有一组卡片,并且想要重新排列整个序列,只需使用 random.shuffle(sequence)用于就地洗牌。

  • 如果您想获得其随机副本,请使用 random.sample()并将长度设置为序列的长度。

<小时/>

这一行:

shuffler = maindeck

假设maindeck是某种可变列表数据结构,shuffler引用与maindeck相同的数据 - 你正在洗牌你的 maindeck (伪装)并返回它 - 再往下你正在操纵它。您可以使用 random.sample() 来代替,它会返回 maindeck 的随机副本。

random.seed() 设置 Mersenne_Twister 的起始内部状态这会产生你的随机性 - 如果需要的话设置一次,但不是每次洗牌时都设置。使用固定值播种您的随机数将产生相同的随机数,因为每个随机操作都会更改内部状态,因此您使用相同的随机操作 - 不需要在没有任何种子的情况下使用它,默认情况下完成在来源中:参见Python's random: What happens if I don't use seed(someValue)?

您的代码应使用random.sample(maindeck,k=len(maindeck))

<小时/>

代码:

import random
random.seed(42) # generate same states if same operations are used

# https://en.wikipedia.org/wiki/Standard_52-card_deck
ranks = ["ace"] + [str(c) for c in range(2,11)] + ["jack", "queen", "king"]
colors = ["clubs","diamonds","hearts","spades"]

def generate_52_card_deck():
"""Returns a new deck of cards. Each card is a tuple of (rank,color)."""
return [ (r,c) for c in colors for r in ranks ]

deck = generate_52_card_deck()
print(deck)

# inplace
random.shuffle(deck)
print(deck)

new_deck = random.sample(deck,k=52)
print("sampled deck: ", new_deck[:10])
print("original deck: ", deck[::5])

输出:

# after generation (shortened)
[('ace', 'clubs'), ('2', 'clubs'), ('3', 'clubs'), ('4', 'clubs'),
('5', 'clubs'), ('6', 'clubs'), ('7', 'clubs'), ('8', 'clubs'),
('9', 'clubs'), ('10', 'clubs'), ('jack', 'clubs'), ('queen', 'clubs'),
('king', 'clubs'),
('ace', 'diamonds'), ('2', 'diamonds'), ('3', 'diamonds'), ('4', 'diamonds'),
('5', 'diamonds'), ('6', 'diamonds'), ('7', 'diamonds'), ... ,
('jack', 'spades'), ('queen', 'spades'), ('king', 'spades')]


# after shuffling once (shortened)
[('10', 'clubs'), ('jack', 'diamonds'), ('king', 'diamonds'), ('4', 'clubs'),
('9', 'diamonds'), ('king', 'hearts'), ('4', 'diamonds'), ('ace', 'spades'),
('7', 'diamonds'), ('queen', 'clubs'), ('8', 'spades'),
('queen', 'diamonds'), ('8', 'hearts'), ('4', 'hearts'), ...,
('9', 'spades'), ('2', 'clubs'), ('8', 'clubs'), ('2', 'spades')]

# first 10 cards ...
sampled deck: [('4', 'spades'), ('king', 'hearts'), ('ace', 'diamonds'),
('jack', 'clubs'), ('queen', 'hearts'), ('2', 'hearts'),
('6', 'diamonds'), ('3', 'spades'), ('8', 'hearts'),
('9', 'diamonds')]

# first 10 cards
original deck: [('10', 'clubs'), ('jack', 'diamonds'), ('king', 'diamonds'),
('4', 'clubs'), ('9', 'diamonds'), ('king', 'hearts'),
('4', 'diamonds'), ('ace', 'spades'), ('7', 'diamonds'),
('queen', 'clubs')]

如果您需要卡值,请使用:

def get_base_card_value(c):
# ace == 11 not done here
v = {"ace":1 ,"jack":10, "queen":10, "king":10}
return v.get(c[0]) or int(c[0])

关于python - python 中 while 循环中 randrange() 的空范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53138966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com