【问题标题】:Coin Flip Simulation硬币翻转模拟
【发布时间】:2018-07-27 20:47:03
【问题描述】:

我刚开始学习 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 循环中,因此它会在继续询问我的输入时不断检查条件。

【问题讨论】:

  • 您能否仔细检查此处显示的代码缩进?它在 Python 中很重要,而且看起来与您的代码中的不同。
  • 建议:这里有很多用 Python 写的关于 SO 的硬币翻转,你可以用谷歌搜索它们并阅读代码。
  • 请阅读ericlippert.com/2014/03/05/how-to-debug-small-programs 开始学习如何调试您的代码。
  • @AntonvBR:我相信我们应该能够告诉 OP 出了什么问题。
  • @usr2564301 假设他正确缩进了所有内容,该程序基本上可以工作。我没有遇到他遇到的问题。

标签: python coin-flipping


【解决方案1】:

我想你一定是在什么地方弄乱了你的缩进。我复制了你的代码,修复了 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 命令应该非常谨慎地使用,因为它很少会改进带有条件的 while 循环、for 循环(如 count_for_sides() 函数)或递归函数(如 num_of_input()) .它通常也比其他结构的可读性差。

【讨论】:

  • 非常感谢您的帮助!我一定把我的缩进搞砸了!!
  • @DanqiLiu 很高兴为您提供帮助!你会随着练习而进步。
【解决方案2】:

这是处理问题的简洁方法,也许可以适应您希望从用户输入中收集 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})

正如其他人所提到的,您的缩进无处不在,但这可以通过反复试验来解决。我跟踪尾部和头部结果的方式是将所有结果保存在一个列表中,然后使用名为“集合”的模块中的 Counter 对象,该模块可以轻松计算元素频率。

【讨论】:

    【解决方案3】:

    我将 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-14
      • 2010-10-03
      • 2019-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多