python itertools permutations code example
Example 1: permutations python
import itertools
print(list(itertools.permutations([1,2,3])))
Example 2: python product
def product(*args, **kwds):
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
Example 3: python itertools repeat()
from itertools import repeat
for x in repeat("Spam? Or Eggs?", 3):
print(x)
> "Spam? Or Eggs?"
> "Spam? Or Eggs?"
> "Spam? Or Eggs?"
Example 4: python combinations
def permutations(iterable, r=None):
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
if r > n:
return
indices = list(range(n))
cycles = range(n, n-r, -1)
yield tuple(pool[i] for i in indices[:r])
while n:
for i in reversed(range(r)):
cycles[i] -= 1
if cycles[i] == 0:
indices[i:] = indices[i+1:] + indices[i:i+1]
cycles[i] = n - i
else:
j = cycles[i]
indices[i], indices[-j] = indices[-j], indices[i]
yield tuple(pool[i] for i in indices[:r])
break
else:
return
Example 5: 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)