Newbie: conventional instead of recursive way

Geoff Gerrietts geoff at gerrietts.net
Wed Dec 18 18:18:00 EST 2002


Quoting Igor Zivkovic (izivkov1 at jagor.srce.hr):
> 
> Thanks, but I'm looking for a pure conventional solution so no recursions 
> are allowed.

I think the word you are looking for is "iterative" not
"conventional".

The iterative solution uses a stack to simulate recursion. As you
encounter each sublist, you "push" the sublist onto your stack and
iterate across the sublist. As you reach the end of each sublist, you
"pop" the stack and return to processing the parent list.

You won't do this using a "for" loop; you're going to need a "while"
loop.

The only advantage (that I am aware of) gained by an iterative
approach is avoiding stack-size limitations imposed by the C
underpinnings of Python. I do not believe (though I have not profiled)
that you will see significant performance differences. You might,
though.

Some pseudocode might help clarify the concept without delivering a
complete solution:

stack is a list
add input to list

while stack has items
  - pop the first item (index 0) off the top list in the stack
  - if the item is a list, stack.append() the list and go back to top
    of loop
  - if the item is printable, print.

Note this algorithm (as written) is destructive; make sure you do a
copy.deepcopy() first if you need the list later.
  
  




-- 
Geoff Gerrietts             "People talk fundamentals and superlatives 
<geoff at gerrietts net>     and then make some changes of detail." 
http://www.gerrietts.net                  --Oliver Wendell Holmes Jr




More information about the Python-list mailing list