Newbi Q: Recursively reverse lists but NOT strings?
Victor B. Gonzalez
python.comp.lang.id982 at vbgunz.com
Mon Oct 15 02:11:27 EDT 2007
On Sunday 14 October 2007 5:06:19 pm Dmitri O.Kondratiev wrote:
> The function I wrote (below) reverses lists all right:
>
> def reverse(xs):
> if xs == []:
> return []
> else:
> return (reverse (xs[1:])) + [xs[0]]
>
> >>> reverse ([1,2,3])
>
> [3, 2, 1]
>
> Yet when I try to reverse a string I get:
> >>> reverse ("abc")
>
> ...
> ...
> ...
>
> File "C:\wks\python-wks\reverse.py", line 5, in reverse
>
> return (reverse (xs[1:])) + [xs[0]]
>
> File "C:\wks\python-wks\reverse.py", line 5, in reverse
>
> return (reverse (xs[1:])) + [xs[0]]
>
> File "C:\wks\python-wks\reverse.py", line 2, in reverse
>
> if xs == []:
>
> RuntimeError: maximum recursion depth exceeded in cmp
>
>
>
> What's wrong? Why recursion never stops?
>
> Thanks,
> Dima
I didn't try anything but it looks like your calling your function in your
else block like this (e.g., reverse('bc')) everytime. your else block isn't
really ending itself, just repeating itself.
I could be wrong but from a quick glance you'll need to end it for sure when
dealing with recursion.
maybe also trying to reverse using the iterator function reversed() or this
shortcut may help e.g, 'abc'[::-1] -> 'cba'.
good luck!
--
Best Regards
Victor B. Gonzalez
More information about the Python-list
mailing list