itertools.py

Created by j-yang19

Created on April 19, 2018

864 Bytes

Implements permutation and combination from the python standard library.

>>> permutations('ABCD', 2)  # AB AC AD BA BC BD CA CB CD DA DB DC
>>> permutations(range(3))  # 012 021 102 120 201 210
>>> combinations('ABCD', 2)  # AB AC AD BC BD CD
>>> combinations(range(4), 3)  # 012 013 023 123


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=list(range(n,n-r,-1))
 yield tuple(pool[i]for i in indices[:r])
 while n:
  for i in range(r-1,0-1,-1):
   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 
def combinations(iterable,r):
 pool=tuple(iterable)
 n=len(pool)
 if r>n:
  return
 indices=list(range(r))
 yield tuple(pool[i]for i in indices)
 while True:
  for i in range(r-1,0-1,-1):
   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)