如何随机选择数学运算符并用它来回答重复的数学问题?

Oba*_*har 5 python random math

我有一个简单的数学任务,我在执行时遇到问题,涉及随机导入.这个想法是有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)
Run Code Online (Sandbox Code Playgroud)

截至目前,我的输出有点搞砸了.例如:

3
6
*
(3, '*', 6)
Run Code Online (Sandbox Code Playgroud)

显然,它无法确定(3,'*',6)的答案.我将把这个操作变成我的其他程序中的子程序,但它需要先工作!

并且请原谅我,如果它做得不好,这是我在学校完成的任务的快速再现,而且我在这方面也是相当新的,知识有限.提前致谢!

Cor*_*mer 21

你怎么制作一个字典,将运营商的角色(例如'+')映射到运营商(例如operator.add).然后对其进行采样,格式化字符串并执行操作.

import random
import operator
Run Code Online (Sandbox Code Playgroud)

生成随机数学表达式

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
Run Code Online (Sandbox Code Playgroud)

问用户

def askQuestion():
    answer = randomCalc()
    guess = float(input())
    return guess == answer
Run Code Online (Sandbox Code Playgroud)

最后做一个多问题的测验

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)
Run Code Online (Sandbox Code Playgroud)

一些测试

>>> 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'
Run Code Online (Sandbox Code Playgroud)