From b514998be5a3b4f222b58995e3caa483a0b4e103 Mon Sep 17 00:00:00 2001 From: "W. Trevor King" Date: Tue, 5 Feb 2013 10:08:52 -0500 Subject: [PATCH] Use question.id instead of question.prompt for answer indexing This decouples the keying from the prompt, which is useful if you want to use another value for the `id` (e.g. a question number). If `id` is not specified, it defaults to `prompt`. --- quizzer/answerdb.py | 14 +++++++------- quizzer/question.py | 8 +++++++- quizzer/ui/cli.py | 2 +- 3 files changed, 15 insertions(+), 9 deletions(-) diff --git a/quizzer/answerdb.py b/quizzer/answerdb.py index 7ba4ba7..3b8aa6c 100644 --- a/quizzer/answerdb.py +++ b/quizzer/answerdb.py @@ -37,23 +37,23 @@ class AnswerDatabase (dict): f.write('\n') def add(self, question, answer, correct): - if question.prompt not in self: - self[question.prompt] = [] - self[question.prompt].append({ + if question.id not in self: + self[question.id] = [] + self[question.id].append({ 'answer': answer, 'correct': correct, }) def get_answered(self, questions): - return [q for q in questions if q.prompt in self] + return [q for q in questions if q.id in self] def get_unanswered(self, questions): - return [q for q in questions if q.prompt not in self] + return [q for q in questions if q.id not in self] def get_correctly_answered(self, questions): return [q for q in questions - if True in [a['correct'] for a in self.get(q.prompt, [])]] + if True in [a['correct'] for a in self.get(q.id, [])]] def get_never_correctly_answered(self, questions): return [q for q in questions - if True not in [a['correct'] for a in self.get(q.prompt, [])]] + if True not in [a['correct'] for a in self.get(q.id, [])]] diff --git a/quizzer/question.py b/quizzer/question.py index 0421fb4..411d5e5 100644 --- a/quizzer/question.py +++ b/quizzer/question.py @@ -1,17 +1,23 @@ class Question (object): - def __init__(self, prompt=None, answer=None, help=None): + def __init__(self, id=None, prompt=None, answer=None, help=None): + if id is None: + id = prompt + self.id = id self.prompt = prompt self.answer = answer self.help = help def __getstate__(self): return { + 'id': self.id, 'prompt': self.prompt, 'answer': self.answer, 'help': self.help, } def __setstate__(self, state): + if 'id' not in state: + state['id'] = state.get('prompt', None) self.__dict__.update(state) def check(self, answer): diff --git a/quizzer/ui/cli.py b/quizzer/ui/cli.py index 9b17339..52b6a83 100644 --- a/quizzer/ui/cli.py +++ b/quizzer/ui/cli.py @@ -29,7 +29,7 @@ class CommandLineInterface (UserInterface): def display_results(self): print('results:') for question in self.quiz: - for answer in self.answers.get(question.prompt, []): + for answer in self.answers.get(question.id, []): self.display_result(question=question, answer=answer) self.display_totals() -- 2.26.2