Doing Your Homework, With Style

As usual in all programming lists, every once in a while someone will post a question in the Python Argentina list which is obviously his homework. To handle that there are two schools of thought.

  1. Telling the student how to do it is helping them cheat.
  2. Telling the student how to do it is teaching him.

I tend more towards 1) but I think I have discovered a middle road:

1.5) Tell the student a solution that's more complicated than the problem.

That way, if he figures out the solution, he has done the work, and if he doesn't figure it out, it's going to be so obviously beyond his skill the teacher will never accept it as an answer.

As an example, here's the problem for which help was requested:

Given an unsorted list of two-letter elements (une lowercase, one uppercase), for example:

['eD', 'fC', 'hC', 'iC', 'jD', 'bD', 'fH', 'mS', 'aS', 'mD']

Sort it by these criteria:

  1. Create subsets according to the uppercase letter, and sort them by the number of members in ascending order, like this:

    ['fH', 'mS', 'aS', 'fC', 'hC', 'iC', 'jD', 'bD', 'eD', 'mD']
  2. Then sort each subset in ascending order of the lowercase letter, like this:

    ['fH', 'aS', 'mS', 'fC', 'hC', 'iC', 'bD', 'eD', 'jD', 'mD']

Ignoring that the problem is not correctly written (there are at least two ways to read it, probably more), I proposed this solution, which requires python 3:

from collections import defaultdict
d1 = defaultdict(list)
[d1[i[1]].append(i) for i in  ['eD', 'fC', 'hC', 'iC', 'jD', 'bD', 'fH', 'mS', 'aS', 'mD']]
{i: d1[i].sort() for i in d1}
d2 = {len(d1[i]): d1[i] for i in d1}
print([item for sublist in [d2[i] for i in sorted(d2.keys())] for item in sublist])

This produces the desired result: ['fH', 'aS', 'mS', 'fC', 'hC', 'iC', 'bD', 'eD', 'jD', 'mD'] but it's done in such a way that to understand it, the student will need to understand roughly three or four things he has probably not been taught yet.