硬币翻转模拟

时间:2018-02-16 21:45:01

标签: python coin-flipping

我刚开始学习Python并试图编写以下问题:

硬币翻转模拟 - 编写一些模拟翻转单个硬币的代码,但用户决定多次。代码应记录结果并计算尾部和头部的数量。

以下是我的代码:

import random

def num_of_input():
   while True:
     try:
        time_flip= int(input('how many times of flips do you want?'))
    except:
        print('please try again')
        continue
    else:
        break

return time_flip    

def random_flip():
   return random.randint(0, 1)


def count_for_sides():
   count_head=0
   count_tail=0
   times=num_of_input()
   while True:
      if count_head+count_tail==times
        break

      else:
          if random_flip()==0:
              count_head+=1
          else:
             count_tail+=1

     print(count_head)
     print(count_tail)

我现在遇到的问题是: 如果我将输入作为x(翻转的x倍),那么我需要输入X + 1次以便能够看到结果,如下所示:

count_for_sides()
how many times of flips do you want?4
how many times of flips do you want?4
how many times of flips do you want?4
how many times of flips do you want?4
how many times of flips do you want?4

 0
 4

我对这种情况感到很困惑。我认为这意味着我的输入函数处于while循环中,因此它会继续检查条件,因为它会继续询问我的输入。

3 个答案:

答案 0 :(得分:0)

我认为你一定是搞砸了某个地方的缩进。我复制了你的代码,修复了SO中的缩进问题,并且它基本上正常工作。

这就是我所拥有的:

import random

def num_of_input():
  while True:
    try:
     time_flip= int(input('how many times of flips do you want?'))
    except:
      print('please try again')
      continue
    else:
      break
  return time_flip    

def random_flip():
  return random.randint(0, 1)


def count_for_sides():
  count_head=0
  count_tail=0
  times=num_of_input()
  while True:
    if count_head+count_tail==times:
      break

    else:
      if random_flip()==0:
        count_head+=1
      else:
        count_tail+=1
  print(count_head)
  print(count_tail)

count_for_sides()

话虽这么说,你正在做一些你不应该做的事情。

首先,有些地方无限循环是合适的,但你的用途不是那些地方。对于第一个函数,我认为像

def num_of_input():
    try:
        time_flip = int(input('how many times of flips do you want?'))
    except ValueError:
        print('That was not a valid integer. Please try again)
        time_flip = num_of_input()
    finally:
        return time_flip

更具可读性和安全性。

对于count_for_sides()函数,类似于:

def count_for_sides:
     count_head, count_tail = 0, 0
     for i in range(num_of_input()):
          if random.randint(0, 1) == 0:
               count_head+=1
          else:
               count_tail+=1
      print(counthead)
      print(counttail)

除了用for循环替换无限while循环之外,我完全摆脱了random_flip函数,因为它什么也没做,只是直接使用了random.randint(0,1)。

通常,python中的break命令应该非常谨慎使用,因为它很少使用条件,for循环(如count_for_sides()函数)或递归函数(如num_of_input())对while循环进行改进。 。它通常也不如其他结构可读。

答案 1 :(得分:-1)

这是处理问题的简洁方法,可能适合您希望从用户输入中收集n_times的代码?

import random
from collections import Counter


def coin_toss(n_times):
  all_outcomes = []
  for x in range(n_times):
    outcome = random.random()
    if outcome > .50:
      all_outcomes.append('H')
    if outcome <= .50:
      all_outcomes.append('T')
  return Counter(all_outcomes)


print(coin_toss(100))

>> Counter({'H': 56, 'T': 44})

正如其他人所提到的那样,你的缩进已经遍布整个地方,但是可以通过一些反复试验来修复。我跟踪尾部和头部结果的方法是将所有结果保存在列表中,然后使用名为“collections”的模块中的Counter对象,这可以轻松地计算元素频率。

答案 2 :(得分:-1)

我把SO的两个解决方案合二为一,做了一个非常简单的抛硬币。它与您的解决方案有一些相似之处,但一切都被剥离了。

import random

def int_input(text):
    """Makes sure that that user input is an int"""
    # source: https://stackoverflow.com/questions/22047671

    while True:
        try:
            num = int(input(text))
        except ValueError:
            print("You must enter an integer.")
        else:
            return num

def main():
    """Asks for amount of tosses and prints sum(heads) and sum(tails)"""
    # source: https://stackoverflow.com/questions/6486877/

    tosses = int_input("How many times of flips do you want? ")

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

    print('The {} tosses resulted in:\n{} heads and {} tails.'
          .format(tosses,heads,tails))    

main()