reduce versus recursion? what am I missing...

Carel Fellinger cfelling at iae.nl
Fri Apr 14 20:29:59 EDT 2000


Warren Postma <embed at geocities.com> wrote:
> # I am trying to figure out why function d (recursive) and e (reduce)
> # DON'T do the SAME thing:

> def d(*tup):
>     "why doesn't this work?"
>     if len(tup)>1:
>         return d(tup[1:])+abs(tup[0]-tup[1])

Wel to start with, why not use a loop?

def m(*tup):
    r = 0 # mind you, you 'seeded' the reduce with 0!
    for t in tup:
	r = abs(r-t)
    return r

You see fast, clear and crisp and no surprises here:)
But if you insist on recursion...

def d(*tup):
    # don't forget the 'seed' value for the recursive 'reduce'
    print "why, it works!",
    return d(0, tup)

def dd(r, tup):
    if len(tup)>0:
	# return d(tup[1:])+abs(tup[0]-tup[1])
	return dd(abs(r-tup[0]), tup[1:])
    else:
        return r

-- 
groetjes, carel



More information about the Python-list mailing list