3

For a school assignment I have to choose two random integers from 0 to 20 and its result (through sub or add which also chooses random) must be in range 0 to 20. For integers and operations I used:

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

Source link for the above code: How can I randomly choose a maths operator and ask recurring maths questions with it?

But i have no idea how to use it in such a way that it can give a result only in range of 0 to 20. Python v3.0 beginner.

Community
  • 1
  • 1

5 Answers5

1

If I am understanding your question correctly, you only want your function to return a result if that result is between 0 and 20. In that case, you could use a while loop until your condition is satisified.

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
Michael Silverstein
  • 1,653
  • 15
  • 17
0

Wrap it in a while as suggested or you could try bounding the second random var as such

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

To ensure you never run out of range.

themistoklik
  • 880
  • 1
  • 8
  • 19
0

You can also use

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')
Gribouillis
  • 2,230
  • 1
  • 9
  • 14
0

You can add modulo 20 operation on the result, so that the result always stays in interval [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
Gennady Kandaurov
  • 1,914
  • 1
  • 15
  • 19
0

You can try to ensure that result will be inside of the bounds, but rules are different for each operation here:

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)
Timofei Bondarev
  • 158
  • 3
  • 12