[英]Generating a result in range of two random integers in range
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: 对于学校作业,我必须选择从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
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. 但是我不知道如何以这样的方式使用它,它只能在0到20的范围内给出结果.Python v3.0初学者。
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. 如果我正确理解你的问题,你只希望你的函数返回结果,如果结果在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
Wrap it in a while as suggested or you could try bounding the second random var as such 根据建议将其包裹一段时间,或者您可以尝试将第二个随机var绑定
a = random.randint (0,20)
b = random.randint (0,20-a)
To ensure you never run out of range. 确保您永远不会超出范围。
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')
You can add modulo 20
operation on the result, so that the result always stays in interval [0, 20)
: 您可以在结果上添加
modulo 20
运算,以便结果始终保持在区间[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
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.