Python 我怎样才能随机选择一个数学运算符并用它提出重复的数学问题?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26260950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:16:56  来源:igfitidea点击:

How can I randomly choose a maths operator and ask recurring maths questions with it?

pythonmathrandom

提问by Obahar

I have a simple maths task I'm having problems executing, involving the random import. The idea is that there is a quiz of 10 randomly generated questions. I've got the numbers ranging from (0,12) using the random.randint function, that works fine. Its the next bit of choosing a random operator I'm having problems with ['+', '-', '*', '/'].

我有一个简单的数学任务,我在执行时遇到问题,涉及随机导入。这个想法是有 10 个随机生成的问题的测验。我使用 random.randint 函数得到了从 (0,12) 范围内的数字,效果很好。它是选择随机运算符的下一点,我在使用 ['+'、'-'、'*'、'/'] 时遇到了问题。

I have my more sophisticated coding back at school, but this is my practise one that all I need is the ability to randomly create a question and ask it, whilst also being able to answer it itself to determine if the answer given is correct. Here's my code:

我在学校有更复杂的编码,但这是我的练习,我所需要的只是随机创建问题并提出问题的能力,同时还能够自行回答以确定给出的答案是否正确。这是我的代码:

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)

As of right now though, my output is a little messed up. For example:

但截至目前,我的输出有点混乱。例如:

3
6
*
(3, '*', 6)

Clearly it can't determine the answer from (3, '*', 6). I'll be turning this operation into a subroutine in my other program, but it needs to work first!

显然它不能从 (3, '*', 6) 确定答案。我将把这个操作变成我另一个程序中的一个子程序,但它需要先工作!

And forgive me if its not very well done, this was a quick recreation of the task I left at school, and I'm also fairly new at this with limited knowledge. Thanks in advance!

如果它做得不好,请原谅我,这是我在学校留下的任务的快速重新创建,而且我对这方面的知识也很陌生。提前致谢!

采纳答案by rwflash

There is a function in Python called eval() that evaluates strings which contain mathematical expressions.

Python 中有一个名为 eval() 的函数,用于计算包含数学表达式的字符串。

import random

ops = ['+', '-', '*', '/']
num1 = random.randint(0,12)
num2 = random.randint(0,10)
operation = random.choice(ops)

print(num1)
print(num2)
print(operation)

maths = eval(str(num1) + operation + str(num2))

print(maths)

You need to convert your numbers to strings because the function is expecting something like the string '4*2', '3+1' etc. etc.

您需要将数字转换为字符串,因为该函数需要类似字符串 '4*2'、'3+1' 等的内容。

回答by Cory Kramer

How about you make a dictionary that maps the operator's character (e.g. '+') to the operator (e.g. operator.add). Then sample that, format you string, and perform the operation.

您如何制作一个将运算符的字符(例如“+”)映射到运算符(例如operator.add)的字典。然后采样,格式化你的字符串,并执行操作。

import random
import operator

Generating a random mathematical expression

生成随机数学表达式

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

Asking the user

询问用户

def askQuestion():
    answer = randomCalc()
    guess = float(input())
    return guess == answer

Finally making a multi-question quiz

最后做一个多问题测验

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)

Some testing

一些测试

>>> 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'

回答by Wayne Askey

Use a list for the operators e.g operator = ['+', '',' -', '/'] then you can use Then you can use random choice on your list to call a random operator (+,-,,/) x = (random.choice(operator)) Finally you will need to convert your num1 & num2 to strings something like this eval(str(num1)+ x + str(num2)) That should make your quiz completly random

使用运算符列表,例如 operator = ['+', ' ',' -', '/'] then you can use Then you can use random choice on your list to call a random operator (+,-,,/ ) x = (random.choice(operator)) 最后,您需要将您的 num1 和 num2 转换为类似这样的字符串 eval(str(num1)+ x + str(num2)) 这应该使您的测验完全随机