[ Write a python function to return nth item or a default value ]
Write a python function to return nth item or a default value
def nth(iterable, n, default=None):
from itertools import islice
return next(islice(iterable, n, None), default)
Write a python function to check whether all elements are equal to each other
def all_equal(iterable):
from itertools import groupby
g = groupby(iterable)
return next(g, True) and not next(g, False)
Write a python function to count how many times the predicate is true
def quantify(iterable, pred=bool):
return sum(map(pred, iterable))
Write a python function to emulate the behavior of built-in map() function
def pad_none(iterable):
"""Returns the sequence elements and then returns None indefinitely.
Useful for emulating the behavior of the built-in map() function.
"""
from itertools import chain, repeat
return chain(iterable, repeat(None))
Write a python function to return the sequence elements n times
def ncycles(iterable, n):
from itertools import chain, repeat
return chain.from_iterable(repeat(tuple(iterable), n))
Write a python function to return the dot product of two vectors
def dotproduct(vec1, vec2):
return sum(map(operator.mul, vec1, vec2))
Write a python function to flatten one level of nesting
def flatten(list_of_lists):
from itertools import chain
return chain.from_iterable(list_of_lists)
Write a python function to repeat calls to function with specified arguments
def repeatfunc(func, times=None, *args):
from itertools import starmap, repeat
if times is None:
return starmap(func, repeat(args))
return starmap(func, repeat(args, times))
Write a python function to convert iterable to pairwise iterable
def pairwise(iterable):
from itertools import tee
a, b = tee(iterable)
next(b, None)
return zip(a, b)
Write a python function to collect data into fixed-length chunks or blocks
def grouper(iterable, n, fillvalue=None):
from itertools import zip_longest
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
Write a python program to create round robin algorithm: "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
def roundrobin(*iterables):
from itertools import islice, cycle
# Recipe credited to George Sakkis
num_active = len(iterables)
nexts = cycle(iter(it).__next__ for it in iterables)
while num_active:
try:
for next in nexts:
yield next()
except StopIteration:
# Remove the iterator we just exhausted from the cycle.
num_active -= 1
nexts = cycle(islice(nexts, num_active))
Write a python function to use a predicate and return entries particition into false entries and true entries
def partition(pred, iterable):
from itertools import filterfalse, tee
# partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
t1, t2 = tee(iterable)
return filterfalse(pred, t1), filter(pred, t2)
Write a python function to return powerset of iterable
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
from itertools import chain, combinations
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
list(powerset([1,2,3]))
Write a python function to list all unique elements, preserving order
def unique_everseen(iterable, key=None):
from itertools import filterfalse
# unique_everseen('AAAABBBCCDAABBB') --> A B C D
# unique_everseen('ABBCcAD', str.lower) --> A B C D
seen = set()
seen_add = seen.add
if key is None:
for element in filterfalse(seen.__contains__, iterable):
seen_add(element)
yield element
else:
for element in iterable:
k = key(element)
if k not in seen:
seen_add(k)
yield element
Write a python function to list unique elements, preserving order remembering only the element just seen.
def unique_justseen(iterable, key=None):
import operator
from itertools import groupby
# unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
# unique_justseen('ABBCcAD', str.lower) --> A B C A D
return map(next, map(operator.itemgetter(1), groupby(iterable, key)))
Write a python function to call a function repeatedly until an exception is raised.
def iter_except(func, exception, first=None):
"""Converts a call-until-exception interface to an iterator interface.
Like builtins.iter(func, sentinel) but uses an exception instead
of a sentinel to end the loop.
Examples:
iter_except(s.pop, KeyError) # non-blocking set iterator
"""
try:
if first is not None:
yield first() # For database APIs needing an initial cast to db.first()
while True:
yield func()
except exception:
pass
def random_product(*args, repeat=1):
import random
pools = [tuple(pool) for pool in args] * repeat
return tuple(map(random.choice, pools))