Russ Adams
Russ Adams

Reputation: 73

Python quiz- how to accept mostly correct answers

I'm writing a program that allows a user to set up personal quizzes (like a notecard-type system). When taking the quiz, the user is timed on each question. The answers aren't going to be multiple choice though, they will be user-inputted.

Is there a way that I can sufficiently accept answers that aren't complete answers of the input they put in when they first set up their quiz?

Example

Q: "Who is Socrates."

A: "A Greek Philosopher."


I thought about using something like:

if input in answer:
    print "That's correct."

But that doesn't work at all.

Is there any possible way to do this? Or something close to it.

---update---

I just recently came across a Python Module that is outstanding at doing this, it's called FuzzyWuzzy and here is a link to it's description and what all it can do http://seatgeek.com/blog/dev/fuzzywuzzy-fuzzy-string-matching-in-python

Upvotes: 1

Views: 1064

Answers (1)

jimhark
jimhark

Reputation: 5046

It depends on exactly what you're trying to do. Your attempt sounds like you are trying to match any substring of "A Greek Philosopher", so "ee" would be a correct answer. That doesn't sound right.

You could have a set (or list) of possible correct answers for each question. For your example maybe you would also accept just "Philosopher".

If you would like to ignore spelling mistakes, you could test if what was entered is "close" to any of the know correct answers. This requires a function that will calculate how close the match is. A popular approach is to use Levenshtein Distance. See:

http://en.wikipedia.org/wiki/Levenshtein_distance
http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Levenshtein_distance
http://code.activestate.com/recipes/576874-levenshtein-distance/
http://pypi.python.org/pypi/python-Levenshtein/

Update

Levenshtein Distance is good if you want to allow inexact spelling. But if you want to allow different phrases, i.e. "A Philosopher from Ancient Greece" then a different approach is required. If you're really motivated, you could try to use NLTK, Natural Language Toolkit for Python to implement a type of fuzzy phrase matching where you try to match parts of speech rather then the exact phrase provided. Be aware, this is not trivial.

Upvotes: 5

Related Questions