[Tutor] very elementary help ... for total analphabet

mikalzet@libero.it mikalzet@libero.it
Sun, 13 Jan 2002 14:20:19 +0100 (CET)


The following code is taken from "Learning to think like a Computer
Scientist with Python":

class Node:
	def __init__(self, cargo=None, next=None):
		self.cargo=cargo
		self.next = next
	def __str__(self):
		return str(self.cargo)

def printBackward(list):
    if list == None: return
    head = list
    tail = list.next
    printBackward(tail)
    print head,

node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node1.next = node2
node2.next = node3
printBackward(node1)

The output is:

3 2 1

Now for the question: I have tried to look at the stack diagram and I've
tried adding print head and print tail commands in various points of
printBackward to see how it works. It seems that:

head = 1 tail = 2
then head = 2 tail = 3
then head = 3 tail = None.
now the 'return' makes the loop exit and "print head" is executed.

(And this already puzzles me, I would have thought return to cause the
whole printBackward() to terminate - therefore no output at all).

This granted, I would expect as output
3

What happens here ?

"print head" seems to be executed several times ( why ?) printing the
succession of values attributed to head in a first-in-last-out manner, as
if it were a stack .... ?

If I don't understand this behaviour I will never be able to use it or change
it. I obviously have a deep misunderstanding of the workings of
recursive functions. Anybody kind enough to explain this example better ?

-- 
Michele Alzetta