7

私は、100回のコイントスをシミュレートし、トスの総数を与えるプログラムをpythonで書いています。問題は、表と裏の合計数も出力したいということです。

これが私のコードです:

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)

私は解決策を求めて頭を悩ませてきましたが、これまでのところ何もありません。トスの総数に加えて、表と裏の数を出力する方法はありますか?

4

11 に答える 11

16
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)
于 2011-06-26T21:35:50.763 に答える
4

試行回数の変数があり、最後にそれを出力できるので、表と裏の数に同じアプローチを使用してください。ループの外側に変数headsと変数を作成し、関連するブロック内でインクリメントしてから、最後に結果を出力します。tailsif coin == X

于 2011-06-26T21:33:24.877 に答える
3
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 ")
于 2015-04-20T19:22:21.053 に答える
1
tosses = 100
heads = sum(random.randint(0, 1) for toss in range(tosses))
tails = tosses - heads
于 2012-01-27T23:39:22.610 に答える
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")))
于 2012-01-27T22:59:28.710 に答える
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
于 2011-06-26T21:43:30.600 に答える
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
于 2012-01-28T09:40:37.797 に答える
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)
于 2011-06-26T21:36:01.917 に答える