itertools.groupby code example
Example 1: intertools combinations implementation
def combinations(iterable, r):
pool = tuple(iterable)
n = len(pool)
if r > n:
return
indices = range(r)
yield tuple(pool[i] for i in indices)
while True:
for i in reversed(range(r)):
if indices[i] != i + n - r:
break
else:
return
indices[i] += 1
for j in range(i+1, r):
indices[j] = indices[j-1] + 1
yield tuple(pool[i] for i in indices)
Example 2: itertools.zip_longest fill value
from itertools import zip_longest
chars = []
correct = 'hangman'
guess = 'winger'
for c, g in zip_longest(correct, guess, fillvalue='_'):
if c == g:
chars.append(c)
else:
chars.append('_')
print(chars)
word = ''.join(chars)
print(word)