как посчитать количество «орлов» и количество «решек», образовавшихся в результате случайного подбрасывания монеты? - PullRequest
0 голосов
/ 09 июля 2020

я хочу подсчитать и вывести количество раз, когда орел и решка выпадают при подбрасывании монеты на основе ввода пользователем количества подбрасываемых монет, которое они хотят.

пока что с этим я не получаю орлов : 1 и количество решек: 1

Я также хочу подсчитать, сколько попыток подбрасывания монеты требуется, чтобы получить список всех орлов, а затем всех решек, но я сначала борюсь с этим!

вот мой код:

# This program simulates tosses of a coin.
import random
heads = "Heads"
tails = "Tails"
count = 0

def main():
    tosses = int(input("Enter number of tosses:")) 
    coin(tosses)
    print("Total number of heads:",(heads.count(heads)))
    print("Total number of tails:", (tails.count(tails)))
    
#end of main function    

def coin(tosses):
    for toss in range(tosses):
        # Simulate the coin toss.
        if random.randint(1, 2) == 1:
            print(heads)
        else:
            print(tails)
    return (heads.count(heads),(tails.count(tails)))
        # end of if statement
     #end of for loop   
#end of coin function

            
# Call the main function.
main()

Ответы [ 3 ]

0 голосов
/ 09 июля 2020

Я внес несколько изменений в ваш код! Это не должно быть таким сложным, как вы его сделали. Дайте мне знать, если у вас возникнут вопросы!

# This program simulates tosses of a coin.
import random

# function to toss coins and increment head/tail counts
def coin(tosses):

    # store the counts of each respective result
    heads = 0
    tails = 0

    for toss in range(tosses):
        # simulate the coin toss
        if random.randint(1, 2) == 1:
            print("Heads!")
            heads+=1 # increment count for heads
        else:
            print("Tails!")
            tails+=1 # increment count for tails

    return heads, tails

# main function
def main():
    # get user input
    tosses = int(input("Enter number of tosses:")) 

    # toss coins
    heads, tails = coin(tosses)

    # print final result
    print("Total number of heads:", heads)
    print("Total number of tails:", tails)


# call the main function
main()
0 голосов
/ 09 июля 2020

Вот альтернативное решение, которое использует модуль collections для возврата количества брошенных орлов и решек:

from random import choice
from collections import Counter

count = int(input("Enter number of tosses: "))
results = Counter([choice(['heads','tails']) for _ in range(count)])
heads, tails = results['heads'], results['tails']

print("total number of heads:", heads)
print("total number of tails:", tails)
0 голосов
/ 09 июля 2020

Эти правки устраняют вашу проблему и соответствуют предыдущим комментариям.

import random
heads = "Heads"
tails = "Tails"
heads_count = 0
tails_count = 0

def main():
    tosses = int(input("Enter number of tosses:"))
    coins = coin(tosses)
    print("Total number of heads:",coins[0])
    print("Total number of tails:", coins[1])

def coin(tosses):
    global heads_count
    global tails_count
    for toss in range(tosses):
        # Simulate the coin toss.
        if random.randint(1, 2) == 1:
            print(heads)
            heads_count+=1
        else:
            print(tails)
            tails_count+=1
    return (heads_count,tails_count)

main()
...