Main Content

Embedding more complex code into a named block

Archive - Originally posted on "The Horse's Mouth" - 2016-11-04 07:38:56 - Graham Ellis

If you're writing a complicated piece of code / awkward algorithm, it's a good idea to put it into a separate function. That way, it can be debugged and tested on its own, it can re-used in other code later on, and it can be hidden away from other users - and indeed from you (the author) unless you need to revisit it.

On our Python courses, one of the exercises we set is to ask delegates to take a list of month lengths:
  mlen = [31,29,31,30,31,30,31,31,30,31,30,31]
and produce two lists - one with 31 x the number 1, then 29 x the number 2 and so on, so that they have an ability to look up (for example) that day 70 of the year is in month three. The second list to contain 1 to 31, the 1 to 29, and so on - so they can also quickly look up which day of the month that day 70 of the year is.

It turns out the the algorithm also works for other things - for example converting working days of the year into week and day number (taking public holidays into account for short weeks, for example!).

Full solution to the original problem - extended beyond what I ask delegates to do in oder to allow code reuse - [here] and an example of that re-use [here]