5.5. Sorting Question - Version 2

To build off of the first question, we’ll use the SortingQuestion_v2 module, located in questions/examples/SortingQuestion_v2/question.py.

5.5.1. Extending SortingQuestion_v1

You will first notice that we inherit from the original SortingQuestion_v1 class. This is a recommended pattern - inherit from base classes to get the boilerplate code of each question out of the way. In this new version, we are only modifying the specifics of clean_instance and validate_answer. So, why re-implement the generate_instance and associated methods?

In reality, you will not be extending from another question. Instead, you will use various base classes for specific question types (arrays, short answers, graph, etc.). This allows for reusability and promotes abstraction - two of our goals to keep in mind.

Let’s look at how we separate common code by utilizing the utils.misc module.

5.5.2. clean_instance

Most of the method is the same that we saw in SortingQuestion_v1. However, there’s this call to copy_dict_specification.

As you can see by viewing that method’s documentation, it accepts a list of fields and outputs the input dictionary with only those fields included.

So,

1
  def validate_answer(self, instance, answer, submission_count):

performs the same job as:

1
2
3
4
      return {
          'prompt': instance['prompt'],
          'original_array': instance['original_array']
      }

5.5.3. validate_answer

Here, we’ve swapped out the array comparison with a call to compare_array. As the name (and documentation) suggests, the method compares two arrays. However, it does not perform a simple equality check. Instead, this method will rate the similarity on a scale of 0 to 1 (just like the grade value we need - what a coincidence!) based on how many elements are similar. It will also ‘deduct’ from the similarity if the second array is longer.

As such, it performs a richer comparison than a simple equality check. This allows for awarding partial credit in a very simple manner - just return the result of compare_array as the grade!

So, we do just that:

1
      response = {

Those are all the changes made. Next, we’ll look into the React.js code that enables the front-end.