Message Boards Message Boards

1 Reply
0 Total Likes
View groups...
Share this post:

How do I compare the output of a cell to a desired result?

Posted 10 years ago

I want to be able to have my students work through questions in a Mathematica notebook and then run a piece of code that compares their solutions to what I want.

I thought along these lines:

NotebookLocate["Q18a"]; SelectionEvaluate[EvaluationNotebook[]];
If[% == 47/12 - 3/2(x + 25/6)^2,"CORRECT", "WRONG"]

Q18a is a Cell Tag for the cell the answer is in. The cell gets evaluated and then the last evaluation (the cell) is compared to the answer. But I keep getting responses like this as the output:

If[Null==47/12 - 3/2(x + 25/6)^2,CORRECT,WRONG]

Anyone able to fix or suggest a better way?

Thanks in advance.

POSTED BY: Miles Ford

See the attached notebook for an example of what you are trying to do. The gist of the reason why your code is not working correctly is that SelectionEvaluate is placing the calculation in the evaluation queue to be executed after the code that contains the SelectionEvaluate. So the % is not referring to the result of the SelectionEvaluate. It's best to be a bit more detailed in the process of getting at the result in the tagged cell and explicitly assigning that expression to a parameter, then checking the parameter against the desired response.

Here is an example of such code and an example notebook that uses it is attached (the cell with the student's answer has the CellTag "testtag)--the code assumes that it is being executed in the notebook itself and that there is only one cell with the given CellTag:

Module[{nb, answer},
 nb = EvaluationNotebook[];
 NotebookFind[nb, "testtag", All, CellTags];
 SelectionMove[nb, All, CellContents];
 answer = ToExpression@NotebookRead[nb];
 If[answer === 1 + x, "Yes!", "No... :-( "]

Note also that I use === rather than ==. The latter might not evaluate to either True or False but the former always will. Also remember that two expressions may be the same but if the pattern on the left hand side is expressed differently than the right hand side then the === will possibly yield False. E.g.,

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


POSTED BY: David Reiss
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract