Self function
bearophileHUGS at lycos.com
bearophileHUGS at lycos.com
Mon May 4 19:06:28 EDT 2009
Carl Banks:
>1. Singly-linked lists can and should be handled with iteration.<
I was talking about a binary tree with list-like topology, of course.
>All recursion does it make what you're doing a lot less readable for almost all programmers.<
I can't agree. If the data structure is recursive (like a tree, or
even sometimes graphs, etc) a recursive algorithm is shorter, more
readable and more natural.
An example, a postorder recursive visit:
def postorder_scan(root):
if root is not None:
if root.left is not None:
for n in postorder_scan(root.left):
yield n
if root.right is not None:
for n in postorder_scan(root.right):
yield n
yield root
Try to write that in an iterative way, not adding any new field to the
nodes, and you will see.
And even if you add a "visited" new boolean field to nodes, the
resulting code isn't as nice as the recursive one yet.
> 2. You should be using a Python list anyway.
I should use D when I have to use such algorithms, I know.
Bye,
bearophile
More information about the Python-list
mailing list