Python代码:硬币抛掷问题

7
我正在使用Python编写一个程序,模拟了100次抛硬币,并且给出了总抛掷次数。但问题在于,我还想打印出正面和反面的总次数。
以下是我的代码:
import random
tries = 0
while tries < 100:
    tries += 1
    coin = random.randint(1, 2)
    if coin == 1:
        print('Heads')
    if coin == 2:
        print ('Tails')
total = tries
print(total)

我一直在想办法解决问题,但目前为止还没有头绪。是否有办法除了总投掷次数外,打印出正反面的次数?


1
在每个if语句中添加一个计数器怎么样(一个用于正面,一个用于反面)? - Fredrik Pihl
1
和计算尝试次数一样...但只有在打印头时才计数。类似于 heads += 1 就可以了 :-) - david van brink
看看"tries"变量的作用,并尝试使用"heads"和"tails"变量复制它。但不要每次都执行heads+=1...你可以想出来的! - Chris Cunningham
11个回答

17
import random

samples = [ random.randint(1, 2) for i in range(100) ]
heads = samples.count(1)
tails = samples.count(2)

for s in samples:
    msg = 'Heads' if s==1 else 'Tails'
    print msg

print "Heads count=%d, Tails count=%d" % (heads, tails)

1
+1 这更接近我们在 Python 中通常做事的方式。释放你的思维,不要试图一步一步地思考,因为正如你已经证明给自己看的那样,这并不容易。考虑你想要完成的任务:“我想要一个包含 100 个硬币翻转的序列;我想要按顺序输出每个硬币翻转的结果为“正面”或“反面”;我想要显示正面和反面的计数”。 - Karl Knechtel
我希望操作者尝试构建几次。这是一个非常好的理解推导的入门(第3行)。 - yurisich
几件事情。(1) 循环计数器i没有被使用,所以可以写成: samples = [random.randint(1, 2) for _ in range(100)]。(2) 可以使用查找表存储结果: messages = {1: "正面", 2: "反面"},循环输出样本结果: for s in samples: print messages[s]。(3) 使用enumerate可能是一个好主意: for i, s in enumerate(samples): print i, messages[s] - hughdbrown

4
import random

total_heads = 0
total_tails = 0
count = 0


while count < 100:

    coin = random.randint(1, 2)

    if coin == 1:
        print("Heads!\n")
        total_heads += 1
        count += 1

    elif coin == 2:
        print("Tails!\n")
        total_tails += 1
        count += 1

print("\nOkay, you flipped heads", total_heads, "times ")
print("\nand you flipped tails", total_tails, "times ")

4

您有一个尝试次数的变量,这使您可以在最后打印它,因此只需使用相同的方法来处理正反面的数量。在循环外创建一个名为 headstails 的变量,在相关的 if coin == X 块内增加,然后在最后打印结果。


P'sao的回答中有代码,但是你提供了解释。我对你和P'sao都表示感谢。 - Ru1138

1

记录头的数量:

import random
tries = 0
heads = 0
while tries < 100:
    tries += 1
    coin = random.randint(1, 2)
    if coin == 1:
        heads += 1
        print('Heads')
    if coin == 2:
        print ('Tails')
total = tries
print('Total heads '.format(heads))
print('Total tails '.format(tries - heads))
print(total)

1
import random
tries = 0
heads=0
tails=0
while tries < 100:
    tries += 1
    coin = random.randint(1, 2)
    if coin == 1:
        print('Heads')
        heads+=1
    if coin == 2:
        print ('Tails')
        tails+=1
total = tries
print(total)
print tails
print heads

1
是的,这是对 OP 代码的最小更改。但并不是真正符合 Python 的习惯用法。 - hughdbrown

1
# Please make sure to import random.

import random

# Create a list to store the results of the for loop; number of tosses are limited by range() and the returned values are limited by random.choice().

tossed = [random.choice(["heads", "tails"]) for toss in range(100)]

# Use .count() and .format() to calculate and substitutes the values in your output string.

print("There are {} heads and {} tails.".format(tossed.count("heads"), tossed.count("tails")))

你实际上没有回答问题 - 你没有计算抛硬币的正反面次数。 - cha0site
@cha0site,我不理解你对问题的解释。这段代码是用来计算正反面的数量的。运行代码并查看结果。 - hughdbrown

1
tosses = 100
heads = sum(random.randint(0, 1) for toss in range(tosses))
tails = tosses - heads

1
你可以使用 random.getrandbits() 一次性生成所有100个随机位:
import random

N = 100
# get N random bits; convert them to binary string; pad with zeros if necessary
bits = "{1:>0{0}}".format(N, bin(random.getrandbits(N))[2:])
# print results
print('{total} {heads} {tails}'.format(
    total=len(bits), heads=bits.count('0'), tails=bits.count('1')))

输出

100 45 55

哦,我不知道 random.getrandombits - hughdbrown

0
这是我的代码。希望能帮到你。
import random

coin = random.randint (1, 2)

tries = 0
heads = 0
tails = 0

while tries != 100:

if coin == 1:
    print ("Heads ")
    heads += 1
    tries += 1
    coin = random.randint(1, 2)

elif coin == 2:
    print ("Tails ")
    tails += 1
    tries += 1
    coin = random.randint(1, 2)
else:
    print ("WTF")

print ("Heads = ", heads)
print ("Tails = ", tails)

2
这几乎是一个复制/粘贴的答案,OP的问题已经得到了回答。 - harmonica141

0
import random

print("coin flip begins for 100 times")

tails = 0
heads = 0
count = 0
while count < 100: #to flip not more than 100 times
count += 1
result = random.randint(1,2) #result can only be 1 or 2.

    if result == 1: # result 1 is for heads
        print("heads")
    elif result == 2: # result 2 is for tails
        print("tails")
    if result == 1:
        heads +=1 #this is the heads counter.
    if result == 2:
        tails +=1 #this is the tails counter.
# with all 3 being the count, heads and tails counters,
# i can instruct the coin flip not to exceed 100 times, of the 100 flips 
# with heads and tails counter, 
# I now have data to display how of the flips are heads or tails out of 100.
print("completed 100 flips") #just to say 100 flips done.
print("total tails is", tails) #displayed from if result == 2..... tails +=1
print("total heads is", heads)

1
也许您可以为其添加一些说明,而不仅是发布一堆代码块。 - johannchopin
抱歉,我已经在我的代码中添加了注释来解释我的逻辑。希望能有所帮助。 - Edward
上面的代码是用来模拟100次抛硬币,显示正反面。还添加了计数器来计算正面和反面的次数,以便在100次抛硬币中知道有多少是正面或反面。最后打印结果以显示计数。 - Edward

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接