On Mon, Feb 21, 2005 at 01:14:00PM -0800, Paul Rubin wrote: > "markscottwright" <[EMAIL PROTECTED]> writes: > > But when I try to do it iteratively, it just hangs when I try to > > evaluate the results (for count > 1): > > > > def repeated2(f, count): > > newfun = f > > for i in range(count-1): > > newfun = lambda x: newfun(f(x)) > > return newfun > > > > For the life of me, I can't figure out why. It seems like for count = > > 2, for example, the results from repeated2 should be lambda x: f(f(x)), > > but it doesn't seem to be. > > It's Python's scoping madness. Try: > > def repeated2(f, count): > newfun = lambda x: x # identity > for i in range(count): > newfun = lambda x, g=newfun: g(f(x)) > return newfun
Ahh, but not sufficienty evil or pernicious. def evil(f, count): def apply_evil(accum, func): return func(accum) def pernicious(x): return reduce(apply_evil, [f]*count, x) return pernicious def f(x): return x+x print evil(f, 3)(2) More seriously I'd go without the recursion and just make a wrapper that applies the function count times in a wrapper. def benign(f, count): def wrap(x): result = f(x) for (i) in range(count-1): result = f(result) return result return wrap print benign(f, 3)(2) -Jack -- http://mail.python.org/mailman/listinfo/python-list