.per items python code example
Example 1: intertools combinations implementation
def combinations(iterable, r):
# combinations('ABCD', 2) --> AB AC AD BC BD CD
# combinations(range(4), 3) --> 012 013 023 123
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)
# ['_', '_', 'n', 'g', '_', '_', '_']
word = ''.join(chars)
print(word)
# __ng___