Skip to main content

Ralsina.Me — Roberto Alsina's website

Doing Your Homework, With Style

As usu­al in all pro­gram­ming list­s, ev­ery once in a while some­one will post a ques­tion in the Python Ar­genti­na list which is ob­vi­ous­ly his home­work. To han­dle that there are two schools of thought.

  1. Telling the stu­­dent how to do it is help­ing them cheat.

  2. Telling the stu­­dent how to do it is teach­ing him.

I tend more to­wards 1) but I think I have dis­cov­ered a mid­dle road:

1.5) Tell the stu­dent a so­lu­tion that's more com­pli­cat­ed than the prob­lem.

That way, if he fig­ures out the so­lu­tion, he has done the work, and if he does­n't fig­ure it out, it's go­ing to be so ob­vi­ous­ly be­yond his skill the teach­er will nev­er ac­cept it as an an­swer.

As an ex­am­ple, here's the prob­lem for which help was re­quest­ed:

Giv­en an un­sort­ed list of two-let­ter el­e­ments (une low­er­case, one up­per­case), for ex­am­ple:

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

Sort it by these cri­te­ri­a:

  1. Cre­ate sub­sets ac­cord­ing to the up­per­case let­ter, and sort them by the num­ber of mem­bers in as­cend­ing or­der, like this:

    ['fH', 'mS', 'aS', 'fC', 'hC', 'iC', 'jD', 'bD', 'eD', 'mD']
  2. Then sort each sub­set in as­cend­ing or­der of the low­er­case let­ter, like this:

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

Ig­nor­ing that the prob­lem is not cor­rect­ly writ­ten (there are at least two ways to read it, prob­a­bly more), I pro­posed this so­lu­tion, which re­quires 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.


Contents © 2000-2024 Roberto Alsina