我有一个简单的数学任务,我在执行时遇到问题,涉及随机导入。 这个想法是有 10 个随机生成的问题的测验。我使用 random.randint 函数得到了 (0,12) 范围内的数字,效果很好。接下来是选择随机运算符我遇到了 ['+', '-', '*', '/'] 的问题。
我在学校有更复杂的编码,但这是我的练习,我需要的是随机创建问题并提出问题的能力,同时还能够自己回答以确定给出的答案是否正确正确的。 这是我的代码:
import random
ops = ['+', '-', '*', '/']
num1 = random.randint(0,12)
num2 = random.randint(0,10)
operation = random.choice(ops)
print(num1)
print(num2)
print(operation)
maths = num1, operation, num2
print(maths)
虽然现在,我的输出有点困惑。 例如:
3
6
*
(3, '*', 6)
显然它无法从 (3, '*', 6) 中确定答案。我将把这个操作变成我的其他程序中的一个子例程,但它需要先工作!
如果做得不是很好,请原谅我,这是对我在学校留下的任务的快速重现,而且我在这方面也相当陌生,知识有限。提前致谢!
最佳答案
如何创建一个字典,将运算符的字符(例如“+”)映射到运算符(例如operator.add
)。然后对其进行采样,格式化字符串,然后执行操作。
import random
import operator
生成随机数学表达式
def randomCalc():
ops = {'+':operator.add,
'-':operator.sub,
'*':operator.mul,
'/':operator.truediv}
num1 = random.randint(0,12)
num2 = random.randint(1,10) # I don't sample 0's to protect against divide-by-zero
op = random.choice(list(ops.keys()))
answer = ops.get(op)(num1,num2)
print('What is {} {} {}?\n'.format(num1, op, num2))
return answer
询问用户
def askQuestion():
answer = randomCalc()
guess = float(input())
return guess == answer
终于做了一道多题测验
def quiz():
print('Welcome. This is a 10 question math quiz\n')
score = 0
for i in range(10):
correct = askQuestion()
if correct:
score += 1
print('Correct!\n')
else:
print('Incorrect!\n')
return 'Your score was {}/10'.format(score)
一些测试
>>> quiz()
Welcome. This is a 10 question math quiz
What is 8 - 6?
2
Correct!
What is 10 + 6?
16
Correct!
What is 12 - 1?
11
Correct!
What is 9 + 4?
13
Correct!
What is 0 - 8?
-8
Correct!
What is 1 * 1?
5
Incorrect!
What is 5 * 8?
40
Correct!
What is 11 / 1?
11
Correct!
What is 1 / 4?
0.25
Correct!
What is 1 * 1?
1
Correct!
'Your score was 9/10'
关于python - 我如何随机选择一个数学运算符并用它提出重复出现的数学问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26260950/