Into itertools
bearophileHUGS at lycos.com
bearophileHUGS at lycos.com
Mon Apr 27 05:38:23 EDT 2009
Arnaud Delobelle:
> Some people would write it as:
>
> def leniter(iterable):
> if hasattr(iterable, '__len__'):
> return len(iteratble)
> return sum(1 for _ in iterable)
That's slower than my version.
> > def xpairwise(iterable):
> > return izip(iterable, islice(iterable, 1, None))
>
> This doesn't work if the iterable is an iterator.
I see. I think I have never used it with an iterator so far :-)
I'll fix it.
> Why not:
>
> def xpairs(seq):
> for i, el in enumerate(seq):
> for j in xrange(i):
> yield seq[j], el
Maybe because I was not smart enough to invent that :-)
-------------------
Mark Dickinson:
> 3) xpairs(seq)
> >>> list(xpairs(range(5)))
> [(0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4), (2, 3),
> (2, 4), (3, 4)]
Doesn't itertools.combinations already do this for you?
>>> list(itertools.combinations(range(5), 2))
I have written most of those functions when I have used Python 2.4,
before itertools.combinations. But you are right, xpairs is now almost
useless, just one line long :-) Combinatorics is so fun :-)
Thank you very much to both.
Bye,
bearophile
More information about the Python-list
mailing list