我正在使用python 3进行基于差异化和集成的课程作业的数学测验。我发现很难检查用户输入的答案是否正确。我目前正在使用以下代码。但是,如果用户键入答案但按不同顺序键入,则将其视为不正确。例如,如果答案是(2,4),但我输入(4 / 2,4),尽管两个答案都是正确的,但它会被视为不正确。我尝试过使用sympify,但它不起作用。我将如何克服这个问题?
def Question4(self):
QID = 109
conn = mysql.connector.connect(user="root", password = "", host = "")
mycursor = conn.cursor()
#mysql query
query = """
SELECT
QText, QAnswer, Marks
FROM
QuestionInfo.Question
WHERE
QID = %s
"""
mycursor.execute(query, (QID, ))
Question4, Answer4, Mark4 = mycursor.fetchone()
self.Answer4 = str(Answer4)
self.Mark4 = Mark4
self.next_question.clicked.connect(self.HandleQuestion4)
def HandleQuestion4(self):
#for validation
reply = QtGui.QMessageBox.question(self, 'Message',
"Are you sure this is your final answer?", QtGui.QMessageBox.Yes |
QtGui.QMessageBox.No, QtGui.QMessageBox.Yes)
#get users answer in a sympy state
self.UAnswer4 = self.Answer.text().replace("^", "**")
if reply == QtGui.QMessageBox.Yes:
if sympify(self.UAnswer4) == sympify(self.Answer4):
self.score = self.score + self.Mark4
else:
self.score = self.score + 0
self.Question5()
答案 0 :(得分:0)
如果您只期望数字,那么您可以在字符串上使用S(同意的简称)。否则,您可能需要使用parse_expr和/或其他字符串处理来处理其他语法,如隐含乘法和" ^"为取幂(见sympy.parsing.sympy_parser):
>>> S('4/2,2')
(2, 2)