Using functional tools
Gerhard Häring
gerhard at bigfoot.de
Wed May 8 04:21:10 EDT 2002
Andrae Muys wrote in comp.lang.python:
> def xmap(func, *args):
> iterlist = [iter(arg) for arg in args]
> while 1:
> yield func(*[itr.next() for itr in iterlist])
Incidentally, yesterday I tried to come up with a little functional
utility library for myself. My xmap looks quite a lot the same ;-) But
in order to be compatible with map, I had to add a special case for
func is None, which I never used in my own code. This is the module:
def xmap(func, *seqs):
"""A lazy map."""
# map defaults to the identity function if func is None:
if func is None:
func = lambda x: x
iters = map(iter, seqs)
while 1:
yield func(*map(lambda x: x.next(), iters))
def xzip(*seqs):
"""A lazy zip."""
iters = map(iter, seqs)
while 1:
# The .next() method on the curiter raises a StopIteration exception
# when it runs out of items. We don't catch it, so it automagically
# stops our generator.
yield tuple([curiter.next() for curiter in iters])
def permutations(items):
"""Yields all permutations of the items."""
if items == []:
yield []
else:
for i in range(len(items)):
for j in permutations(items[:i] + items[i+1:]):
yield [items[i]] + j
def combinations(items, k=None):
"""Yields all k-combinations of items."""
if k is None:
k = len(items)
if k == 0:
yield []
else:
for i in items:
for j in combinations(items, k-1):
yield [i] + j
Gerhard
--
mail: gerhard <at> bigfoot <dot> de registered Linux user #64239
web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930
public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))
More information about the Python-list
mailing list