生成两个随机整数范围内的结果

3

我需要选择两个随机整数,范围是0到20,并通过加法或减法得出结果,结果必须在0到20的范围内。为了生成这些随机整数和操作,我使用了以下方法:

def random():
    op={"-": operator.sub, "+": operator.add}
    a = random.randint (0,20)
    b = random.randint (0,20)

    ops = random.choice(list(op.keys()))
    answer=op[ops](a,b)
    return answer

以上代码的源链接:如何随机选择数学运算符并重复提问?

但我不知道如何使用它以使结果仅在0到20的范围内。Python v3.0初学者。


做一个 while 循环,直到你的结果令人满意是一种方法。 - themistoklik
5个回答

1
如果我正确理解了你的问题,你只想在结果介于0和20之间时返回函数结果。在这种情况下,你可以使用while循环直到满足条件为止。
def random():
    while True:
        op={"-": operator.sub, "+": operator.add}
        a = random.randint (0,20)
        b = random.randint (0,20)

        ops = random.choice(list(op.keys()))
        answer=op[ops](a,b)
        if answer in range(0,20):
            return answer

0
将其包装在一个while循环中,如建议所述,或者您可以尝试限制第二个随机变量如下。
a = random.randint (0,20)
b = random.randint (0,20-a)

确保您永远不会超出范围。


0

你也可以使用

for ops in random.sample(list(op), len(op)):
    answer = op[ops](a, b)
    if 0 <= answer <= 20:
        return answer
raise RuntimeError('No suitable operator')

0

您可以在结果上添加 模20 操作,以便结果始终保持在区间 [0, 20):

def random():
    op={"-": operator.sub, "+": operator.add}
    a = random.randint (0,20)
    b = random.randint (0,20)

    ops = random.choice(list(op.keys()))
    answer=op[ops](a,b)

    return answer % 20

0

你可以尝试确保结果在范围内,但每个操作的规则都不同:

op = {"-": operator.sub, "+": operator.add}
ops = random.choice(list(op))
if ops == '+':
    a = random.randint(0, 20)      # a in [0; 20]
    b = random.randint(0, 20 - a)  # b in [0; 20 - a]
else:  # ops == '-'
    a = random.randint(0, 20)  # a in [0; 20]
    b = random.randint(0, a)   # b in [0; a]

answer = op[ops](a, b)  # answer will be in [0; 20]
print(a, ops, b, '=', answer)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接