【问题标题】:generate sum of results in python在python中生成结果总和
【发布时间】:2017-02-04 13:20:45
【问题描述】:

我们有一个游戏,游戏包含 500 轮。在每一轮中,两个硬币同时滚动,如果两个硬币都有“正面”,那么我们赢 1 英镑,如果两个都有“反面”,那么我们输 1 英镑,如果我们遇到一个硬币显示“正面”的情况',而另一枚硬币显示“反面”,反之亦然,然后我们就“再试一次”。

coin_one = [random.randint(0, 1) for x in range(500)]
coin_two = [random.randint(0, 1) for x in range(500)]

game = zip(coin_one, coin_two)

for a, b in game:
    if a and b:
        print(1)
    elif not a and not b:
        print(-1)
else:
    print('please try again') # or continue

这样的结果是:

1 请再试一次 -1 请再试一次 请再试一次 请再试一次 -1 -1 1 -1 ,............, 1

我试图找出结果的总和,以便在游戏完成(500 轮)后知道游戏玩家赢或输了多少。

在获得只玩一场游戏(500 轮)的结果(总赢/输)后,我希望玩游戏 100 次,以创建一些汇总统计数据,例如玩这个游戏的平均值、最大值、最小值和标准差.

【问题讨论】:

  • 您可以在for 循环之前有一个变量sum = 0,而不是打印1 和-1,并将这些值添加到sum 变量中。在循环结束时,您将获得赢/输的总金额

标签: python random simulation montecarlo coin-flipping


【解决方案1】:

您可以简单地将值的总和累加到一个新变量中:

total = 0
for a, b in game:
    if a and b:
        total += 1
    elif not a and not b:
        total -= 1
    else:
        print('please try again')

print(total)

如果你不想打印任何东西,以防它们都有不匹配的值,你可以做一个单行:

s = sum(0 if a^b else (-1, 1)[a and b] for a, b in game)

请注意,^ 是 xor 运算符,如果两个操作数相同,则返回 falsy 值。把它放在一个三元中,我们可以通过使用and 两个操作数的快捷方式的结果进行索引来选择-1 或1。

【讨论】:

    【解决方案2】:

    正如其他人所建议的,total 是您想要搜索的内容。在循环之前定义它,然后它在循环中进入/递减。

    total = 0
    for a, b in game:
        if a and b:
            total += 1
        elif not a and not b:
            total -= 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-01
      • 1970-01-01
      • 2016-04-08
      • 2016-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      相关资源
      最近更新 更多