[Tutor] Help with range of months spanning across years

Steven D'Aprano steve at pearwood.info
Wed Feb 2 20:17:19 CET 2011


ian douglas wrote:
> It bugs me that so many people are quick to jump on the "we wont' do 
> your homework" bandwagon -- I was accused of the same thing when I 
> posted a question to the list myself. I've been programming 
> professionally for many years but learning Python in my spare time... I 
> sent this reply to Sean privately, but frankly I'm so annoyed at the 
> 'homework' replies, I figured I'd just post it here.

It's a fine line. Most people consider "homework" questions to be 
cheating, and don't want to either condone or assist cheaters in any 
way. The cost, though, is occasionally offending people who aren't 
cheating, but merely asking a question poorly, or happen to be asking 
something that *sounds* like homework, or just unlucky.

Generally, if you want an answer to a question, you should demonstrate 
that you've tried to solve it yourself. Code, even broken code that 
doesn't work, and a clear description of the problem, go a long way to 
assuring people that *even if it is homework*, you've made a good 
attempt at the problem and are looking for *help* rather than somebody 
to do it for you.

At which point somebody will almost certainly jump in an do it for you :)


> I'm still very junior to Python, but this seems to work for me using 
> recursion. I'm sure there's a much more elegant way of doing this, but 
> like I said, I'm still pretty new to the language.
> 
> def makelist(startmonth,startyear,endmonth,endyear):
>     mylist = []
>     if (startyear == endyear):
>         for month in range (startmonth,endmonth+1):
>             mylist += [(startyear,month)]
>     else:
>         for month in range (startmonth,13):
>             mylist += [(startyear,month)]
>         mylist += makelist(1,startyear+1, endmonth, endyear)
>     return mylist ;
> 
> print makelist(8,2009,1,2010)
> 
> I'd love to hear any replies from the experts on the list on how to make 
> this more efficient in Python 'cause I'm still learning myself.

Generally, you don't use recursion because it's efficient, 'cos it 
ain't. At least not in Python, which has a fairly naive recursion model. 
Some other languages can spot a particular kind of recursion, and 
optimise the bejeezus out of it. So leave recursion for the problems 
where (1) it makes solving the problem easy, and (2) the inefficiency 
doesn't matter.

The *general* way of making recursion efficient is by converting it to 
iteration, if possible. In your case, recursion doesn't seem to really 
make the problem any easier to solve, but it probably doesn't hurt much.


-- 
Steven


More information about the Tutor mailing list