繁体   English   中英

当两个随机数相等时的'if'语句

[英]'if' statement for when two random numbers are equal

我正在尝试一种情况,当我们同时扔两个硬币时,如果两个硬币都正面朝上,则赢了,如果两个硬币都背面朝上,则输了。

我已经能够使用以下方法生成抛硬币之一的结果:

def coin_one():
one = [random.randint(1, 100) for x in range(100)]
for x in one:
    if x <= 50:
        print('Heads')
    else:
        print('Tails')

对于第二枚硬币,也使用基本相同的方法:

def coin_two():
two = [random.randint(1, 100) for x in range(100)]
for x in two:
  if x <= 50:
    print('Heads')
  else:
    print('Tails')

我试图添加一个条件,当两个硬币同时投掷时,如果coin_one和coin_two中都有“ heads”,则将打印('win')。 我该怎么做呢?

为什么不将两种计算都用一种方法结合起来,而检查却要一遍呢? 由于您要随机投币; 二进制值0/1足以准确表示此概率( 使用它们的隐式bool值进行相等性检查会带来额外的好处 )。

def coin_toss():
    first_coin_tosses = [random.randint(0, 1) for x in range(100)]
    second_coin_tosses = [random.randint(0, 1) for x in range(100)]

    for first_coin_toss, second_coin_toss in zip(first_coin_tosses, second_coin_tosses):
        if first_coin_toss and second_coin_toss:  # Both 1's
            # We win.
        elif not first_coin_toss and not second_coin_toss:  # Both 0's
            # We lose.
        else:
            # if we get a 1 on one coin and and 0 on the other 
            # or vice versa then we neither win nor lose (we try again).

编写两个函数,这些函数将返回1-100之间的随机值。 然后在诸如firstnum> 50和secondnun> 50的条件下写:打印头Else:打印尾

您可以通过以下两种方式之一来实现结果。
第一种方法:
这是直接的解决方案。 将所有硬币一和硬币二的结果存储在一个列表中,并将其返回到调用方法并检查是否相等。

第二种方法:
您可以为每个硬币1和2值返回(实际收益),并在调用方法中进行检查。

import random

def coin_one():
    one = [random.randint(1, 100) for x in range(100)]
    for x in one:
       if x <= 50:
           print('Heads')
           #Use yield to return value and also continue method execution
           yield 'Heads' #Add this line
       else:
           print('Tails')
           yield 'Tails' #Add this line


def coin_two():
    two = [random.randint(1, 100) for x in range(100)]
    for x in two:
       if x <= 50:
           print('Heads')
           yield 'Heads'
       else:
           print('Tails')
           yield 'Tails'

coin_1_result = coin_one()
coin_2_result = coin_two()
for coin_1, coin_2 in zip(coin_1_result, coin_2_result):
    if coin_1 == 'Heads' and coin_2 == 'Heads':
        print('win')
    else:
        print('loss')

==运算符用于检查两个原始值(int,字符串)是否相等

yield通过将每个结果发送到调用函数而不返回或退出被调用方法(coin_one()或coin_two())来帮助构建列表。

zip(a,b)允许同时迭代两个可迭代对象(例如:list)。 即,它将在第一次迭代中返回coin_1_result [0],coin_2_result [0],在第二次迭代中将返回coin_1_result [1],coin_2_result [1],依此类推。

此外,您还可以注意到,从这两个函数产生第一组值后,赢或输的结果将立即打印出来。

样本输出:

尾巴
失利


赢得

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM