Let's Talk About Lambda Functions!

Bengt Richter bokr at oz.net
Tue Aug 6 11:54:42 EDT 2002


On 6 Aug 2002 01:21:18 -0700, tebeka at cs.bgu.ac.il (Miki Tebeka) wrote:

>Hello Brit,
>
>> So I know what lambda functions are, they're syntax and how they're used.
>> However I'm not sure *why* one would use a lambda function. What's the
>> advantage that they offer over a regular function?
>
>Warning: I've bee a Scheme believer before I've converted to Python
>:-)
>
>Sometime lambda functions yeild more (IMO) elegant solution that is 
>easier to read and understand.
>One example is success/fail continuations.
>
Couldn't resist ;-) Borrowing and modifying your code, you might find
this solution interesting (I modified your tree display to make it
easier to follow the branches):
--< treex.py >------------------------------------
class Tree:
    '''Simple binary tree'''
    def __init__(self, val, lson=None, rson=None):
        self.val = val
        self.lson = lson
        self.rson = rson

    def display(self, indent = 0, label=''):
        print '%s%s%s' % ('  ' * indent, label, self.val)
        if self.lson:
            self.lson.display(indent + 1, 'L:')
        if self.rson:
            self.rson.display(indent + 1, 'R:')

class Success(Exception):
    def __init__(self, crumbs): self.crumbs= crumbs

def path2(t, v):
    '''Find path to v in t'''
    try:
        sfpath2(t, v, '')
        return "Couldn't find path to %s" % v
    except Success, s:
        return 'Found %s by walking %s from tree root' % (v, s.crumbs)

def sfpath2(t, v, crumbs):
    '''raise Success solution'''
    if not t: return  # Can't find
    if t.val == v: # Found right here
        raise Success(crumbs or 'nowhere')
    # Recursive case, explore subtrees
    sfpath2(t.lson, v, crumbs+'L')
    sfpath2(t.rson, v, crumbs+'R')

t = Tree(1,
        Tree(2,
            Tree(3)),
        Tree(4,
            Tree(5)))

def test(t,x):
    print path2(t, x)  
--------------------------------------------------
 >>> import treex
 >>> treex.t.display()
 1
   L:2
     L:3
   R:4
     L:5
 >>> treex.test(treex.t, 5)
 Found 5 by walking RL from tree root
 >>> treex.test(treex.t, 3)
 Found 3 by walking LL from tree root
 >>> treex.test(treex.t, 4)
 Found 4 by walking R from tree root
 >>> treex.test(treex.t, 9)
 Couldn't find path to 9
 >>> treex.test(treex.t, 1)
 Found 1 by walking nowhere from tree root

Regards,
Bengt Richter



More information about the Python-list mailing list