python - 我如何随机选择一个数学运算符并用它提出重复出现的数学问题?

标签 python math random

我有一个简单的数学任务,我在执行时遇到问题,涉及随机导入。 这个想法是有 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/

相关文章:

python - 如果 Pandas 不可用,则添加列

java - 各种形状的面积和周长计算

python - 如何优化对库函数(例如 random.random)的多次调用?

gcc - boost::uniform_on_sphere 在几百万次正确实现后突然失败,但仅限于某些主机

arrays - 使用基本操作的解决方案查找算法

java - 在java中获取特定范围内的随机数

python - 当我的内核对这个 DataFrame 进行热编码时,是否应该继续死掉?

Python3.2 : Installing MySQL-python fails with error "No module named ConfigParser"

python - 从 Python-Docx 中的单元格中删除段落

algorithm - 如何从球体表面上的当前点(纬度/经度)找到线段上的最近点