a for循环应返回10个值的列表。它返回带有随机数的列表
我正在自动化无聊的东西课程中的硬币翻转挑战。 我必须计算总共100个条纹的6个头或6个尾巴条纹的几率。
因此,第一步是在分配了H或T的每个项目中产生一个列表,因此在第二步中,我们可以在列表中搜索6个条纹。 从Python和编码开始时,当我在挑战方面遇到麻烦时,我喜欢进行练习。使用我知道我需要制定最终程序的概念编写一个小程序。
import random
Heads=0
Tails=0
exper=[]
for i in range(10):
if random.randint(0, 1)==0:
exper.append('H')
Heads=Heads + 1
if random.randint(0, 1)==1:
exper.append('T')
Tails = Tails + 1
print (exper)
print (Heads)
print(Tails)
所需输出的一个例子是
['H','T','H','T','H','T','H','T','H','T']
我不知道我是否在做错了什么,但是它应该正常工作。 带有T和H的列表
我的输出是 很好地解释了。此网站的第一个问题。
I´m doing the coin flip challenge from the automate the boring stuff course.
I have to calculate the odds of a 6 heads or 6 tails streak occuring for a total of 100 streaks.
So, first step is to produce a list with each item assigned either H or T so in the second step we can search for 6 streaks in the list.
As i am starting with python and coding, when i am having trouble with a challenge, i like to do a practice run. Write a small program using concepts that i know i will need to make the final program.
import random
Heads=0
Tails=0
exper=[]
for i in range(10):
if random.randint(0, 1)==0:
exper.append('H')
Heads=Heads + 1
if random.randint(0, 1)==1:
exper.append('T')
Tails = Tails + 1
print (exper)
print (Heads)
print(Tails)
An example of the desired output would be something like
['H','T','H','T','H','T','H','T','H','T']
i dont know if im doing something wrong, but it should work properly.
My output is a list with T´s and H´s in it but the length of the list is random...sometimes its a list with 2 items, others with 10, or even 14.
Thanks in advance and i hope i have explained it well. First question here in this site.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在调用
Random.randint
在循环的每次迭代中两次。每个人都可能产生1或0。考虑如果第一个调用Randy.randint
产生0
,而下一个会产生1
1 。这将导致h
和at
在循环的相同迭代中附加到列表中。相反的情况也可能发生,导致没有附加的值。因此,在循环的每次迭代中,您都可以附加零,一个或两个值。由于它不是头,因此必须是尾巴,一个选项是添加
else
而不是randy.randint
的另一个调用。这应该始终产生10个值:
You are calling
random.randint
twice in each iteration of the loop. It's possible each one produces 1 or 0. Consider what happens if the first call torandom.randint
produces a0
and the next one produces a1
. This would cause both anH
and aT
to be appended to the list in the same iteration of the loop. The opposite can happen too resulting in no value appended.So in each iteration of the loop you can append zero, one, or two values. Since if it's not heads, it must be tails, one options would be to add an
else
instead of another call torandom.randint
.Which should consistently produce 10 values: