[Tutor] Understanding error in recursive function

Oliver Bestwalter oliver at bestwalter.de
Fri Apr 8 19:08:23 EDT 2016


Hi Tom,


You can see what happens for yourself in the Pythontutor:
http://goo.gl/YVkh03 - step through the code by clicking on "Forward" and
see what happens. You are calling the howMany function from inside the
function itself, which is called recursion. This can be practical, but in
your case it isn't. In other langauges, the function would call itself
until you run out of memory, but in Python there is an (adjustable) limit
to the number of recursion that can be executed, before the error occurs
that you describe.


One simple rewrite of your function that counts alle elements of all lists
in the dictionary (I am not sur if that's what you want, but I guess you
can figure out what you need from the example) is this: http://goo.gl/frZfkc

animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']}
x = animals['a']

def how_many(aDict):
      count = 0
      for value in animals.values():
           count += len(value)
      return count

print(how_many(x))

(hope the pasted code is not mangled ...)

cheers
Oliver

On Sat, 9 Apr 2016 at 00:52 Tom Maher <tomjmaher4 at gmail.com> wrote:

> Hi,
>
> As a test I am trying to write a function that returns the sum of values
> attached to one key in a dictionary. I am wondering why the code that I
> wrote is returning:
> "maximum recursion depth exceeded "
> Here is the code:
>
> animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']}
>
> x = animals['a']
>
> def howMany(aDict):
>
>       count = 0
>
>       for value in howMany(aDict):
>
>            count += 1
>
>       return count
>
> howMany(x)
>
>
> Just wondering why I would be getting that error.
>
>
> Thanks
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list