[英]Why when i randomly select a number to be put into a list it always picks the same starting number?
This is the code.这是代码。 I'm learning Python and I tried writing a Blackjack script that can calculate the odds of ending up with an X sized hand while having 21 or below.我正在学习 Python 并且我尝试编写一个二十一点脚本,该脚本可以计算在拥有 21 或以下时以 X 大小的手结束的几率。 The code is supposed to keep appending random cards out of the deck until it reaches a set amount of cards.该代码应该不断地从牌组中添加随机牌,直到达到一定数量的牌。 (I know decks aren't usually infinite, it's just an experiment) (我知道套牌通常不是无限的,这只是一个实验)
If it goes over 21 before X amount of cards in hand it discards the hand and starts a new hand.如果它在 X 手牌数量之前超过 21,它会丢弃手牌并开始新手牌。
But for some reason every time it starts a new hand that hand list starts with the same first integer as all previous hands like this:但由于某种原因,每次开始新手牌时,手牌列表都以与之前所有手牌相同的第一个 integer 开头,如下所示:
Can someone please explain to me what I'm doing wrong?有人可以向我解释我做错了什么吗?
[8, 3, 2, 6, 2]
[8, 2, 3, 2, 5]
[8, 2, 2, 4, 3]
[8, 6, 2, 2, 2]
[8, 2, 2, 2, 7]
[8, 4, 5, 2, 2]
[8, 5, 2, 2, 2]
[8, 2, 2, 2, 6]
[8, 2, 2, 6, 3]
[8, 3, 6, 2, 2]
[8, 6, 2, 2]
total amount of hands: 1020
the percentage of 7 card hands that total 21 or less is 1 in 10.2
import random
card_deck = [2,3,4,5,6,7,8,9,10,11]
def blackjack_tracker(deck):
hand = []
trackers = 0
count = 0
ace = 0
x = 0
while trackers <10:
if len(hand) < 7:
hand.append(random.choice(deck))
if len(hand) == 7 and sum(hand) <= 21:
print(hand)
hand.pop(all(hand))
trackers += 1
count += 1
elif len(hand) == 7 and sum(hand) > 21:
hand.pop(all(hand))
count += 1
print(hand)
print('total amount of hands: {}'.format(count))
print('the percentage of 7 card hands that total 21 or less is 1 in {}'.format(count/10))
blackjack_tracker(card_deck)
The code that you use for "it discards the hand and starts a new hand" is:您用于“丢弃手牌并开始新手牌”的代码是:
hand.pop(all(hand))
which doesn't discard the whole hand (the meaning of this expression is explained later).它不会丢弃整只手(这个表达式的含义稍后解释)。
You should use either:你应该使用:
hand.clear()
or或者
hand = []
Integesting is the meaning of the hand.pop(all(hand))
method. Integesting 是hand.pop(all(hand))
方法的意思。 Because what it really does is popping the second element of the non-empty array.因为它真正做的是弹出非空数组的第二个元素。
Because all(hand)
always returns True and hand.pop(True)
is being cast to hand.pop(1)
and it removes the element at position 1 from the array.因为all(hand)
总是返回 True 并且hand.pop(True)
被强制转换为hand.pop(1)
并且它从数组中删除了 position 1 处的元素。
That's the reason the element in position '0' is never touched - because you never remove it.这就是 position '0' 中的元素永远不会被触及的原因 - 因为你永远不会删除它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.