[英]blackjack game: for loops 'not in' vs 'in'
I have run into some trouble using for loops while making a blackjack game simulation. 在进行二十一点游戏模拟时,在使用for循环时遇到了一些麻烦。 The function
new_game
simulates four cards being dealt, while new_card
ensures no card is repeated in a game. 函数
new_game
模拟了要发行的四张牌,而new_card
确保了游戏中不会重复发牌。 I created two variations of the function new game
and was wondering how they differ. 我创建了
new game
功能的两个变体,想知道它们之间的区别。
In Version 1, there were situations where the function only returned 3 cards, while Version 2 seems to work as expected. 在版本1中,有些情况下该函数仅返回3张卡,而版本2似乎按预期运行。
Version 1: 版本1:
def new_game():
game=[];
for x in range(4):
n=new_card();
if n not in game:
game+=[n];
else:
new_game();
print(game);
return game
Version 2: 版本2:
def new_game():
game=[];
for x in range(4):
n=new_card();
if n in game:
new_game();
print(game);
else:
game+=[n];
return game
Calling new_game
is not the best way to solve this project. 调用
new_game
并不是解决此项目的最佳方法。 You can try multiple ways , one of which I am showing. 您可以尝试多种方式,我正在展示其中一种。 Rather than a constant for loop try to check the length of list until it is of desired length.
而不是常量的循环尝试检查列表的长度,直到它是所需的长度。
def new_game():
game=[];
while len(game)!=4:
n = new_card()
while(n in game):
n = new_card()
else:
game.append(n)
return game
print new_game()
I am not sure if this is a good design but still it works and you may modify it. 我不确定这是否是一个好的设计,但仍然可以使用,您可以对其进行修改。
EDIT 编辑
Thanks to Blckknght for suggesting this. 感谢Blckknght提出的建议。
def new_game():
game=[]
while len(game)!=4:
n = new_card()
if n not in game:
game.append(n)
return game
print new_game()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.