[Tutor] Understanding error in recursive function

Alan Gauld alan.gauld at btinternet.com
Fri Apr 8 20:55:26 EDT 2016


On 09/04/16 00:34, Martin A. Brown wrote:

> You start by creating a dictionary that uses an initial letter as 
> the key and a list to hold the names of the animals.  Your function 
> could probably be as simple as:
> 
>   def howMany(aList):
>         return len(aList)
> 

> Here is an inefficient function that demonstrates these principles 
> of recursion:
> 
>   def howMany(l, count=0):
>       if not l:  # -- termination condition, empty list!
>           return count
>       return howMany(l[1:], count+1)
> 

> Given that your question was recursion, I chose to focus on that, 
> but I would recommend using the simplest tool for the job, and in 
> this case that would be the builtin function called 'len'.

Just to round off Martin's discussion we should probably
consider the non recursive option without using len().
It's still pretty simple:

def howMany(aList):
    count = 0
    for item in aList:
        count += 1
    return count

or a slightly sneaky but faster version:

def howMany(aList):
    return aList.index(aList[-1]) + 1

But the len() function does what you want so in practice
just use that.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list