Nicer way to write folding? (list reversal?)
andrew at acooke.org
andrew at acooke.org
Wed Jan 2 16:27:52 EST 2002
Hi,
In the code below, foldr2 is clearly uglier than the rest. Is there a
nicer way (without destructive reversal - yuck - of the list
argument)? Also, are these things built-in (can't find them)? Is
recursion any faster than it used to be (I've not been following
Python development so am wondering if anything in 2 (or 2.2) would
help; foldr2 and fold2 are expected to be faster than foldl and foldr,
although I've not done any timing).
Thanks,
Andrew
# foldr: f(x1, f(x2, ... f(xn-1, f(xn, c))...))
# foldl: f(xn, f(xn-1, ... f(x2, f(x1, c))...))
def foldr(action, start, list):
if not list: return start
else: return action(list[0], foldr(action, start, list[1:]))
def foldl(action, start, list):
if not list: return start
else: return foldl(action, action(list[0], start), list[1:])
def foldr2(action, start, list):
for i in range(len(list), 0, -1): start = action(list[i-1], start)
return start
def foldl2(action, start, list):
for x in list: start = action(x, start)
return start
print foldr(operator.add, "x", ["a", "b", "c"])
print foldl(operator.add, "x", ["a", "b", "c"])
print foldr2(operator.add, "x", ["a", "b", "c"])
print foldl2(operator.add, "x", ["a", "b", "c"])
abcx
cbax
abcx
cbax
--
http://www.acooke.org
More information about the Python-list
mailing list