Check if two math answers are equivalent

2019-07-07 01:16发布

问题:

I'm writing a small app in python which lets users answer math questions. The problem I'm having is checking their answers.

Say there's a question like: "Factorise x^2 + 3x +2"

There are different ways to answer this; for example:

  • (x + 1)(x + 2)
  • (x + 2)(x + 1)
  • (2 + x)(x + 1)
  • etc.

Is there a library which will check if an answer is equivalent to another? Particularly one which doesn't simplify the given answer; so:

(x + 1)(x + 2) === (2 + x)(x + 1)

But

(x + 1)(x + 2) !== x^2 + 3x +2

I thought about using wolframalpha for this — would this be possible — and if so what syntax should I use?

Thanks!

回答1:

You could try using a symbolic math library like sympy.

Call the simplify logic on both your answer and the one supplied by the user. Running the logic on both addresses this issue noted in the documentation:

exact strategies this function tries can change in the future versions of SymPy



回答2:

Yeah Wolfram Alpha will handle this (just stick your conditions into the search and it'll return a boolean value).

You obviously don't want to do that for each one so you could turn to the Wolfram Alpha API. They have a Python library and it's free for non-commercial use, up to 2000 calls per month. If you need commercial calls or more calls, they have monthly tariffs.

There are local options (like Python) but you'll likely have more problems with syntax, formatting, making sure your users aren't passing in malicious Python code and just supporting everything. The WA-API should remove most of the problems for you but test it first.



回答3:

You may want to look at wims. AFAIK it is not written in python, but it is open source, so you can look at the code and get some ideas.



回答4:

I don't think you need a library for something like that. You have the user input limited to answers your program understands (strings that make sense) and then do the reverse operation to find if their answer is correct by matching the question, or take the easy way out and have radio button multiple choice. So using your example you have your program expand out the answer they give, and check it against x^2 + 3x +2.



回答5:

You may try using SymPy. It may help solving your problem. http://docs.sympy.org/dev/gotchas.html#double-equals-signs