Newbie: conventional instead of recursive way

Bengt Richter bokr at oz.net
Thu Dec 19 19:19:02 EST 2002


On 19 Dec 2002 16:19:21 GMT, grante at visi.com (Grant Edwards) wrote:

>In article <atqvnf$j5e$1 at bagan.srce.hr>, Igor Zivkovic wrote:
>> Steve Holden <sholden at holdenweb.com> wrote:
>> 
>>> You can look as long as you like. What makes you feel that recursion is
>>> "unconventional"? It's a perfectly valid technique for dealing with
>>> recursive data structures, and in fact the most natural way to handle them.
>>> Or is this purely an intellectual exercise? I just don't see what you hope
>>> to gain by avoiding recursion.
>> 
>> I know that the proper way to do it is with recursion. I shouldn't 
>> have called it unconventional though, sorry. Its just an exercise I can't 
>> solve. I've read in some tutorial it can be done using loops but it didn't 
>> give any examples and I can't figure it out on my own. I was hoping 
>> someone could at least give me a hint.
>
>IMO, recursion is the only way to do it.  You can use the
>interpreter's call stack to keep track of where you are, or you
>can build a stack explicitly in your program and manipulate it
>inside a loop.
>
>The latter is just simulating the former.
>
Or you can borrow python's recursive work by recognizing that its repr
output is flat if you ignore "extraneous" characters ;-)

 >>> a = [1,2,[3,[4,5],6,[7,8,],9],10]
 >>> repr(a)
 '[1, 2, [3, [4, 5], 6, [7, 8], 9], 10]'
 >>> repr(a).translate(''.join([chr(i) for i in range(256)]),'[,]')
 '1 2 3 4 5 6 7 8 9 10'
 >>> print repr(a).translate(''.join([chr(i) for i in range(256)]),'[,]')
 1 2 3 4 5 6 7 8 9 10

I post this thinking it's probably outside of the box wrt the homework ;-)

BTW, it would be handy if translate would accept None as the first argument
as an indicator to use identity translation, when you just want the deletion part.
Or is there another way to do that?

Regards,
Bengt Richter



More information about the Python-list mailing list