Recursively traverse linked list -- help!

Cliff Wells logiplexsoftware at earthlink.net
Tue Feb 19 21:00:57 EST 2002


On 19 Feb 2002 17:46:30 -0800
Jason wrote:

> # I am a Python novice so I don't really understand how things
> # work, yet.  So some of this may either be wrong or not the
> # Python way.  Also I have no idea why the 'if __name__ == ...'
> # construct is needed instead of just the naked main statements.

It isn't "needed".  It's typically used so that a module can provide a
built-in test/example.  When you use "import ll" this code will not be
executed because __name__ will not be "__main__".  If you put just the
naked main statements, you will need to comment them out before you import
them into another program or else they'll get executed (unless that's what
you want) upon import.

> # A few notes on the code.  There are two solutions: list_naked
> # and list.
> #
> # list_naked is the simplies solution, it has no wrapper object
> # and each node in list_naked is the head of a list.  You can see
> # the recursion in list_naked.sum() and list_naked.__str_all(),
> # where you will notice the if statements that test for the
> # base case of the recursion.
> #
> # list_wrapped is a little more complex.  It has a wrapping object
> # that is always used to refer to the list (unlike list_naked
> # where the head of the list can change when a new value is pushed,
> # hence the ll = ll.push(ll,x) assignment).  Here, the recursion
> # is stopped by the_list_wrapped_empty_node and all the control
> # flow is done by the interpreter.  I like this best, because I
> # hate explicit control flow in programs and I think that it makes
> # it easier to see the forest instead of the trees.  Looking at
> # list_wrapped.sum() it is clear: add this node to the sum of the
> # rest.  In list_naked.sum() you now have to look at two statements
> # which do the same thing semantically.  With list_wrapped there
> # is no way to forget to check for your base case because you don't
> # check anything!  With just a list it seems a little too much,
> # but when you start playing with various tree types and graphs
> # it makes the code so much more readable.

I'm not seeing a question here.  Are you simply asking if your code is
"pythonic"?

> # Also, can somebody help me find the documentation to the builtin
> # procedures, like print().  I checked the __builting__ module docs
> # but there is nothing there.  Thanks

print is a statement, not a procedure (which is why you don't need
parentheses when using it), and hence is located in the language reference,
not the library reference.


-- 
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 x308  (800) 735-0555 x308




More information about the Python-list mailing list