是否可以打印全部内容而不是打印每个动作的百分比

时间:2019-06-09 22:15:16

标签: python-3.x for-loop random range

我尝试编写一个coinToss模拟器,对于初学者来说这很容易,但是随后,我尝试实现一个百分比系统,该百分比系统计算总翻转的正面或反面的百分比。那是当我注意到我被困住并且可能需要一些帮助的时候。

我试图打破for循环并排除x变量到print的所有内容

import random


heads = "Heads"
tails = "Tails"
flips = int(input("How many flips do you want to toss?: "))
print("................................")
cointoss = [(heads), (tails)]


for flips in range(flips):
    toss = random.choice(cointoss)
    print(toss)
    X = toss.count(heads)
    Y = toss.count(tails)
    Z = 100/(int(X)+int(Y))
    print('Percent of X: '+str(X*Z)+'%')
    print('Percent of Y: '+str(Y*Z)+'%')

这是结果



How many flips do you want to toss?: 4
................................
Heads
Percent of X: 100.0%
Percent of Y: 0.0%
Heads
Percent of X: 100.0%
Percent of Y: 0.0%
Heads
Percent of X: 100.0%
Percent of Y: 0.0%
Tails
Percent of X: 0.0%
Percent of Y: 100.0%

我希望代码显示整个循环的总百分比,而不是根据结果显示正面或反面的100%。

3 个答案:

答案 0 :(得分:2)

尝试一下;

import random

Headcount=0
Tailcount=0
heads = "Heads"
tails = "Tails"
flips = int(input("How many flips do you want to toss?: "))
print("................................")
cointoss = [(heads), (tails)]


for flips in range(flips):
    toss = random.choice(cointoss)
    If toss == heads:
        Headcount+=1
    else:
        Tailcount+=1
    print(toss)
    X = Headcount
    Y = Tailcout
    print('Percent of X: '+str((X/X+Y)*100)+'%')
    print('Percent of Y: '+str((Y/Y+X)*100)+'%')

答案 1 :(得分:1)

您需要一些额外的变量,这些变量将计算到目前为止的头和尾的总数,以及至今为止完成的当前翻转次数。现在,您所拥有的方式目前尚无任何有关头/尾的总数的信息,仅是当前翻转的结果,因此您无法准确计算百分比。

我建议在循环外部添加变量,以供总头数和总尾数使用。每当您进行翻转时,都将增加适当的计数器,然后可以基于这些计数器计算总的头/尾的百分比。

答案 2 :(得分:1)

首先,您没有正确计算百分比,因为在进行过程中您没有保持当前旋转次数的计数。您可以做的是使用旋转的当前索引来计算以下百分比:

percentageOfHeads = currentNumberOfHeads / currentNumberOfFlips * 100

percentageOfTails = currentNumberOfTails / currentNumberOfFlips * 100

import random

heads = "Heads"
tails = "Tails"
numHeads = 0
numTails = 0
flips = int(input("How many flips do you want to toss?: "))
print("................................")
cointoss = [heads, tails]


for flip in range(flips):
    toss = random.choice(cointoss)

    if toss == heads:
        numHeads += 1
    else:
        numTails += 1

    print("Flip #" + str(flip + 1) + ": " + toss)

    percentHeads = numHeads / (flip + 1) * 100
    percentTails = numTails / (flip + 1) * 100

    print('Percent of Heads: ' + str(percentHeads) + '%')
    print('Percent of Tails: ' + str(percentTails) + '%')