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

时间:2016-12-08 07:06:14

标签: python python-3.x

对于学校作业,我必须选择0到20之间的两个随机整数,其结果(通过sub或add也选择随机)必须在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

上述代码的来源链接:How can I randomly choose a maths operator and ask recurring maths questions with it?

但是我不知道如何以这样的方式使用它,它只能在0到20的范围内给出结果.Python v3.0初学者。

5 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

按照建议将其包裹一段时间,或者您可以尝试将第二个随机变量绑定为

a = random.randint (0,20)
b = random.randint (0,20-a)

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

答案 2 :(得分: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')

答案 3 :(得分:0)

您可以对结果添加modulo 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

答案 4 :(得分: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)
相关问题