13

我对 Python 非常陌生,我必须创建一个模拟掷硬币的游戏,并要求用户输入应该掷硬币的次数。基于该响应,程序必须为指定的次数选择一个随机数,该数是 0 或 1(并决定哪个代表“正面”,哪个代表“反面”)。计算产生的“正面”数量和“反面”数量,并向用户呈现以下信息:由模拟抛硬币组成的列表,以及产生的正面数量和反面数量的摘要。例如,如果用户输入 5,则抛硬币模拟可能会导致 ['heads', 'tails', 'tails', 'heads', 'heads']。程序应打印如下内容:“ ['heads', 'tails', 'tails', 'heads', 'heads']

这是我到目前为止所拥有的,它根本不起作用......

import random

def coinToss():
    number = input("Number of times to flip coin: ")
    recordList = []
    heads = 0
    tails = 0
    flip = random.randint(0, 1)
    if (flip == 0):
        print("Heads")
        recordList.append("Heads")
    else:
        print("Tails")
        recordList.append("Tails")
    print(str(recordList))
    print(str(recordList.count("Heads")) + str(recordList.count("Tails")))
4

13 回答 13

13

你需要一个loop来做到这一点。我建议一个for循环:

import random
def coinToss():
    number = input("Number of times to flip coin: ")
    recordList = []
    heads = 0
    tails = 0
    for amount in range(number):
         flip = random.randint(0, 1)
         if (flip == 0):
              print("Heads")
              recordList.append("Heads")
         else:
              print("Tails")
              recordList.append("Tails")
    print(str(recordList))
    print(str(recordList.count("Heads")) + str(recordList.count("Tails")))

我建议您在循环中阅读此内容for

此外,您可以number作为参数传递给函数

import random
def coinToss(number):
    recordList, heads, tails = [], 0, 0 # multiple assignment
    for i in range(number): # do this 'number' amount of times
         flip = random.randint(0, 1)
         if (flip == 0):
              print("Heads")
              recordList.append("Heads")
         else:
              print("Tails")
              recordList.append("Tails")
    print(str(recordList))
    print(str(recordList.count("Heads")) + str(recordList.count("Tails")))

然后,您需要在最后调用该函数:coinToss().

于 2013-02-14T19:32:01.383 回答
7

你快到了:

1)您需要调用该函数:

coinToss()

2)您需要设置一个循环来random.randint()重复调用。

于 2013-02-14T19:30:30.557 回答
3

我会采取以下方式:

from random import randint
num = input('Number of times to flip coin: ')
flips = [randint(0,1) for r in range(num)]
results = []
for object in flips:
        if object == 0:
            results.append('Heads')
        elif object == 1:
            results.append('Tails')
print results
于 2013-02-14T19:58:13.300 回答
3

这可能更 Pythonic,虽然不是每个人都喜欢列表推导式。

import random

def tossCoin(numFlips):      
    flips= ['Heads' if x==1 else 'Tails' for x in [random.randint(0,1) for x in range(numflips)]]
    heads=sum([x=='Heads' for x in flips])
    tails=numFlips-heads
于 2013-10-07T22:41:30.583 回答
2
import random
import time



flips = 0
heads = "Heads"
tails = "Tails"

heads_and_tails = [(heads),
                   (tails)]
while input("Do you want to coin flip? [y|n]") == 'y':
    print(random.choice(heads_and_tails))
    time.sleep(.5)
    flips += 1


else:
    print("You flipped the coin",flips,"times")
    print("Good bye")

你可以试试这个,我有它,所以它会问你是否要掷硬币,然后当你说不或 n 时,它会告诉你掷硬币的次数。(这是在 python 3.5 中)

于 2018-05-03T01:54:42.510 回答
1

创建一个包含 head 和 tail 两个元素的列表,并从 random 中使用choice() 来获得掷硬币的结果。要获取 head 或 tail 出现的次数,请将计数附加到列表中,然后使用集合中的 Counter(list_name) 。使用 uin() 调用

##coin flip
import random
import collections
def tos():
    a=['head','tail']
    return(random.choice(a))
def uin():
    y=[]
    x=input("how many times you want to flip the coin: ")
    for i in range(int(x)):
        y.append(tos())
    print(collections.Counter(y))
于 2019-08-13T18:45:17.947 回答
0

我是这样做的。可能不是最好和最有效的方法,但是现在您有不同的选择可供选择。我做了 10000 次循环,因为练习中已经说明了这一点。

#Coinflip program
import random

numberOfStreaks = 0
emptyArray = []
for experimentNumber in range(100):
#Code here that creates a list of 100 heads or tails values
headsCount = 0
tailsCount = 0
#print(experimentNumber)
for i in range(100):
    if random.randint(0, 1) == 0:
        emptyArray.append('H')
        headsCount +=1
    else:
        emptyArray.append('T')
        tailsCount += 1   

#Code here that checks if the list contains a streak of either heads or tails of 6 in a row
heads = 0
tails = 0
headsStreakOfSix = 0
tailsStreakofSix = 0

for i in emptyArray:
    if i == 'H':
        heads +=1
        tails = 0
        if heads == 6:
            headsStreakOfSix += 1
            numberOfStreaks +=1
            
    if i == 'T':
        tails +=1
        heads = 0
        if tails == 6:
            tailsStreakofSix += 1
            numberOfStreaks +=1
            
#print('\n' + str(headsStreakOfSix))
#print('\n' + str(tailsStreakofSix))
#print('\n' + str(numberOfStreaks))
print('\nChance of streak: %s%%' % (numberOfStreaks / 10000))
于 2021-01-03T10:40:43.473 回答
0

而不是所有这些,你可以这样做:

import random
options = ['Heads' , 'Tails']
number = int(input('no.of times to flip a coin : ')
for amount in range(number):
   heads_or_tails = random.choice(options)
   print(f" it's {heads_or_tails}")
print()
print('end')
于 2020-01-18T08:55:38.227 回答
0

解决眼前的问题

最高投票的答案实际上并没有运行,因为它将一个字符串传递给range()(而不是一个 int)。

这是一个解决两个问题的解决方案:刚刚提到的问题,以及最后两行语句中的调用可以变得多余range()的事实。编写此代码段是为了尽可能少地修改原始代码。str()print()

def coinToss():
    number = int(input("Number of times to flip coin: "))
    recordList = []
    heads = 0
    tails = 0
    for _ in range(number):
        flip = random.randint(0, 1)
        if (flip == 0):
            recordList.append("Heads")
        else:
            recordList.append("Tails")
    print(recordList)
    print(recordList.count("Tails"), recordList.count("Heads"))

更简洁的方法

但是,如果您正在寻找更简洁的解决方案,则可以使用列表推导。只有一个其他答案具有列表推导,但您可以嵌入从{0, 1}{"Heads", "Tails"}使用一个而不是两个列表推导的映射:

def coinToss():
    number = int(input("Number of times to flip coin: "))
    recordList = ["Heads" if random.randint(0, 1) else "Tails" for _ in range(number)]
    print(recordList)
    print(recordList.count("Tails"), recordList.count("Heads"))
于 2022-03-03T05:13:47.007 回答
0
#program to toss the coin as per user wish and count number of heads and tails
import random
toss=int(input("Enter number of times you want to toss the coin"))
tail=0
head=0
for i in range(toss):
    val=random.randint(0,1)
    if(val==0):
        print("Tails")
        tail=tail+1
    else:
        print("Heads")
        head=head+1
print("The total number of tails is {} and head is {} while tossing the coin {} times".format(tail,head,toss))
    
于 2021-04-14T15:47:15.220 回答
-1
import random

def coinToss(number):
    heads = 0
    tails = 0
    for flip in range(number):
        coinFlip = random.choice([1, 2])

        if coinFlip == 1:
            print("Heads")
            recordList.append("Heads")
        else:
            print("Tails")
            recordList.append("Tails")

number = input("Number of times to flip coin: ")
recordList = []
if type(number) == str and len(number)>0:
    coinToss(int(number))
    print("Heads:", str(recordList.count("Heads")) , "Tails:",str(recordList.count("Tails")))
于 2019-12-16T15:06:19.633 回答
-1
heads = 1
tails = 0 

input("choose 'heads' or 'tails'. ").upper()

random_side = random.randint(0, 1)

if random_side == 1:
    print("heads you win")
else:
    print("sorry you lose ")
于 2021-10-31T18:58:10.027 回答
-1

抛 N 枚硬币的所有可能性

def Possible(n, a):
    if n >= 1:
        Possible(n // 2, a)
    z = n % 2
    z = "H" if z == 0 else "T"
    a.append(z)
    return a


def Comb(val):
    for b in range(2 ** N):
        A = Possible(b, [])
        R = N - len(A)
        c = []
        for x in range(R):
            c.append("H")
        Temp = (c + A)
        if len(Temp) > N:
            val.append(Temp[abs(R):])
        else:
            val.append(Temp)
    return val


N = int(input())
for c in Comb([]):
    print(c)
于 2021-09-20T13:32:41.017 回答