From 8e02b9b9774fdd596761b809d92a0b72de8b0456 Mon Sep 17 00:00:00 2001 From: Miguel BarĂ£o Date: Tue, 5 Nov 2019 23:32:34 +0000 Subject: [PATCH] text-regex questions now accept also a list of regular expressions to match. It's considered correct if any match is found. --- aprendizations/questions.py | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/aprendizations/questions.py b/aprendizations/questions.py index 539342c..cb15512 100644 --- a/aprendizations/questions.py +++ b/aprendizations/questions.py @@ -257,8 +257,11 @@ class QuestionTextRegex(Question): '''An instance of QuestionTextRegex will always have the keys: type (str) text (str) - correct (str with regex) + correct (str or list[str]) answer (None or an actual answer) + + The correct strings are python standard regular expressions. + Grade is 1.0 when the answer matches any of the regex in the list. ''' # ------------------------------------------------------------------------ @@ -267,19 +270,29 @@ class QuestionTextRegex(Question): self.set_defaults(QDict({ 'text': '', - 'correct': '$.^', # will always return false + 'correct': ['$.^'], # will always return false })) + # make sure its always a list of regular expressions + if not isinstance(self['correct'], list): + self['correct'] = [self['correct']] + + # make sure all elements of the list are strings + self['correct'] = [str(a) for a in self['correct']] + # ------------------------------------------------------------------------ def correct(self) -> None: super().correct() if self['answer'] is not None: - try: - ok = re.match(self['correct'], self['answer']) - except TypeError: - logger.error(f'While matching regex {self["correct"]} with ' - f'answer {self["answer"]}.') - self['grade'] = 1.0 if ok else 0.0 + self['grade'] = 0.0 + for r in self['correct']: + try: + if re.match(r, self['answer']): + self['grade'] = 1.0 + return + except TypeError: + logger.error(f'While matching regex {self["correct"]} with' + f' answer "{self["answer"]}".') # ============================================================================ @@ -421,8 +434,8 @@ class QuestionInformation(Question): # To generate an instance of a question we use the method generate(). # It returns a question instance of the correct class. # There is also an asynchronous version called gen_async(). This version is -# synchronous for all question types (radio, checkbox, etc) except for generator -# types which run asynchronously. +# synchronous for all question types (radio, checkbox, etc) except for +# generator types which run asynchronously. # # Example: # -- libgit2 0.21.2