Kaydet (Commit) 2ec5fd54 authored tarafından Raymond Hettinger's avatar Raymond Hettinger

Document another recipe for itertools: all_equal(). Inspired by David Beazley.

üst 87640b30
...@@ -695,6 +695,11 @@ which incur interpreter overhead. ...@@ -695,6 +695,11 @@ which incur interpreter overhead.
"Returns the nth item or a default value" "Returns the nth item or a default value"
return next(islice(iterable, n, None), default) return next(islice(iterable, n, None), default)
def all_equal(iterable):
"Returns True if all the elements are equal to each other"
g = groupby(iterable)
return next(g, True) and not next(g, False)
def quantify(iterable, pred=bool): def quantify(iterable, pred=bool):
"Count how many times the predicate is true" "Count how many times the predicate is true"
return sum(imap(pred, iterable)) return sum(imap(pred, iterable))
......
...@@ -1525,6 +1525,11 @@ Samuele ...@@ -1525,6 +1525,11 @@ Samuele
... "Returns the nth item or a default value" ... "Returns the nth item or a default value"
... return next(islice(iterable, n, None), default) ... return next(islice(iterable, n, None), default)
>>> def all_equal(iterable):
... "Returns True if all the elements are equal to each other"
... g = groupby(iterable)
... return next(g, True) and not next(g, False)
>>> def quantify(iterable, pred=bool): >>> def quantify(iterable, pred=bool):
... "Count how many times the predicate is true" ... "Count how many times the predicate is true"
... return sum(imap(pred, iterable)) ... return sum(imap(pred, iterable))
...@@ -1623,6 +1628,9 @@ perform as purported. ...@@ -1623,6 +1628,9 @@ perform as purported.
>>> nth('abcde', 9) is None >>> nth('abcde', 9) is None
True True
>>> [all_equal(s) for s in ('', 'A', 'AAAA', 'AAAB', 'AAABA')]
[True, True, True, False, False]
>>> quantify(xrange(99), lambda x: x%2==0) >>> quantify(xrange(99), lambda x: x%2==0)
50 50
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment