Python Tutorial

Saturday, May 4, 2013

Itertools - Combinatoric generators

  • product: Equivalent to nested for-loops in a generator expression.
  • permutations: Return successive r length permutations of elements in the iterable.
  • combinations: Return r length subsequences of elements from the input iterable.
  • combinations_with_replacement: Return r length subsequences of elements from the input iterable allowing individual elements to be repeated more than once.
import itertools

A = [ 1, 2, 3]
B = [4]
C = [5, 6]

print "product example:"
s=[ A, B, C ]
print list(itertools.product(*s))


print "permutations example:"
i = 1
for n in itertools.permutations(A,3):
  print i,":",n
  i += 1


print "combinations example:"  
i = 1
for n in itertools.combinations("ABCD",3):
  print i,"[:]",n
  i += 1

print "combinations_with_replacement example:"    
print list( itertools.combinations_with_replacement("ABD",3))


Output:
product example:
[(1, 4, 5), (1, 4, 6), (2, 4, 5), (2, 4, 6), (3, 4, 5), (3, 4, 6)]
permutations example:
1 : (1, 2, 3)
2 : (1, 3, 2)
3 : (2, 1, 3)
4 : (2, 3, 1)
5 : (3, 1, 2)
6 : (3, 2, 1)
combinations example:
1 [:] ('A', 'B', 'C')
2 [:] ('A', 'B', 'D')
3 [:] ('A', 'C', 'D')
4 [:] ('B', 'C', 'D')
combinations_with_replacement example:
[('A', 'A', 'A'), ('A', 'A', 'B'), ('A', 'A', 'D'), ('A', 'B', 'B'), ('A', 'B', 'D'), ('A', 'D', 'D'), ('B', 'B', 'B'), ('B', 'B', 'D'), ('B', 'D', 'D'), ('D', 'D', 'D')]

0 comments:

Post a Comment