_json.dump(
data, f, indent=2, separators=(',', ': '), sort_keys=True)
f.write('\n')
+
+ def leaf_questions(self):
+ "Questions that are not dependencies of other question"
+ dependents = set()
+ for question in self:
+ dependents.update(question.dependencies)
+ return [q for q in self if q.id not in dependents]
+
+ def get(self, id=None):
+ matches = [q for q in self if q.id == id]
+ if len(matches) == 1:
+ return matches[0]
+ elif len(matches) == 0:
+ raise KeyError(id)
+ raise NotImplementedError(
+ 'multiple questions with one ID: {}'.format(matches))
class UserInterface (object):
"Give a quiz over a generic user interface"
- def __init__(self, quiz=None, answers=None):
+ def __init__(self, quiz=None, answers=None, stack=None):
self.quiz = quiz
if answers is None:
answers = _answerdb.AnswerDatabase()
self.answers = answers
+ if stack is None:
+ stack = quiz.leaf_questions()
+ self.stack = stack
def run(self):
raise NotImplementedError()
raise NotImplementedError()
def get_question(self):
- remaining = self.answers.get_unanswered(questions=self.quiz)
- if remaining:
- return remaining[0]
+ if self.stack:
+ print(self.stack)
+ return self.stack.pop(0)
def process_answer(self, question, answer):
correct = question.check(answer)
self.answers.add(question=question, answer=answer, correct=correct)
+ if not correct:
+ self.stack.insert(0, question)
+ for qid in reversed(question.dependencies):
+ self.stack.insert(0, self.quiz.get(id=qid))
return correct