[Tutor] Problem with python

Dave Kuhlman dkuhlman at rexx.com
Wed Oct 20 23:03:15 CEST 2010

On Wed, Oct 20, 2010 at 03:02:43AM +0600, Matthew Nunes wrote:
>    To whom it may concern,
>                                       Hi, I've just started learning how
>    to program in python using Allan B. Downy's book "How to think like a
>    computer scientist" and it explained something in the recursion
>    chapter which have still been unable to understand. It wrote a piece
>    of code for the factorial function in math for example 3! is 3 * 2 *
>    1. I cannot understand the how it claimed the code executed, and
>    logically it makes no sense to me. Please explain it to me, as I have
>    spent hours trying to get my head around it, as the book(in my
>    opinion) did not explain it well. Here it is:
>    def factorial(n):
>    if n == 0:
>    return 1
>    else:
>    recurse = factorial(n-1)
>    result = n * recurse
>    return result
>    If there is and easier piece of code that you know of that can be used
>    for factorial, if you could please also tell me that.
>    Thank you for your time.

The other replies have helped you understand that recursive
function.  But, recursion gets especially interesting when it is
applied to recursive data structures, for example data whose
structure is the same as the data that it contains.  A tree
structure whose nodes all have the same structure is a good

The code that follows constructs a tree out of objects that are
instances of class Node, then walks that tree and prints it out. 
This code provides two recursive ways to walk and display that
tree: (1) the "show" method in class Node and (2) the "shownode"

Often processing recursive structures like trees is trivial with a
recursive function or method.

Keep in mind that this code is well behaved only when the data
structure we apply it to has a reasonable maximum depth.

Hope this example helps.

- Dave

# ============================================================
class Node(object):
    def __init__(self, data, children=None):
        self.data = data
        if children is None:
            self.children = []
            self.children = children
    def show(self, level):
        print '%sdata: %s' % ('    ' * level, self.data, )
        for child in self.children:
            child.show(level + 1)

def shownode(node, level):
    print '%sdata: %s' % ('    ' * level, node.data, )
    for child in node.children:
        child.show(level + 1)

def test():
    n1 = Node('aaaa')
    n2 = Node('bbbb')
    n3 = Node('cccc')
    n4 = Node('dddd')
    n5 = Node('eeee', [n1, n2])
    n6 = Node('ffff', [n3, n4])
    n7 = Node('gggg', [n5, n6])
    print '=' * 20
    shownode(n7, 0)

# ============================================================

Dave Kuhlman

More information about the Tutor mailing list