a few extensions for the itertools
Steven D'Aprano
steve at REMOVE.THIS.cybersource.com.au
Sun Nov 19 16:51:17 EST 2006
On Sun, 19 Nov 2006 21:35:24 +0100, Mathias Panzenboeck wrote:
> I wrote a few functions which IMHO are missing in python(s itertools).
>
> You can download them here:
> http://sourceforge.net/project/showfiles.php?group_id=165721&package_id=212104
>
> A short description to all the functions:
>
> icmp(iterable1, iterable2) -> integer
> Return negative if iterable1 < iterable2,
> zero if iterable1 == iterable1,
> positive if iterable1 > iterable1.
What does it mean for an iterable to be less than another iterable? That
it has fewer items? How do these two iterables compare?
iter([1, 2, None, "foo", 3+2j])
def ones():
while 1:
yield 1
Which is smaller?
> isum(iterable, start=0) -> value
> Returns the sum of the elements of a iterable
> plus the value of parameter 'start'. When the
> iterable is empty, returns start.
You mean just like the built-in sum()?
>>> sum(xrange(12), 1000)
1066
> iproduct(iterable, start=0) -> value
> Returns the product of the elements of a iterable
> times the value of parameter 'start'. When the
> iterable is empty, returns start.
If I recall, product() was requested about the same time that sum() was
introduced, and Guido rejected it as a built-in because it was really only
useful for calculating geometric means, and it is easy to do if you need
it:
def product(it, start=1):
# default value of 1 is more sensible than 0
# 1 is the multiplicative identity
p = start
for x in it:
p *= x
return p
> forall(predicate, iterable, default=True) -> bool
> Returns True, when for all elements x in iterable
> predicate(x) is True. When the iterable is empty,
> returns default.
>
>
> forany(predicate, iterable, default=False) -> bool
> Returns True, when for any element x in iterable
> predicate(x) is True. When the iterable is empty,
> returns default.
I vaguely recall plans for all() and any() builtins -- perhaps for Python
2.5?
> take(n,iterable) -> iterator
> returns a iterator over the first n
> elements of the iterator
Just like itertools.islice(iterable, n).
>>> list(itertools.islice(xrange(10), 5))
[0, 1, 2, 3, 4]
> drop(n,iterable) -> iterable
> drops the first n elemetns of iterable and
> return a iterator over the rest
Just like itertools.islice(iterable, n, None)
>>> list(itertools.islice(xrange(20), 15, None))
[15, 16, 17, 18, 19]
(Aside: I think islice would be so much cleaner if it took keyword
arguments.)
> heads(iterable) -> iterator over all heads
> tails(iterable) -> iterator over all tails
What would you use these for?
> fcain(funct,*functs) -> function(...,***)
> fcain(f1,f2,...,fn)(*args,*kwargs) equals f1(f2(...fn(*args,*kwargs)))
The usual term for this is function composition.
--
Steven.
More information about the Python-list
mailing list