Skip to content

Instantly share code, notes, and snippets.

@IndhumathyChelliah
Created July 7, 2020 02:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IndhumathyChelliah/be9ae610810f32486dc458fe64714315 to your computer and use it in GitHub Desktop.
Save IndhumathyChelliah/be9ae610810f32486dc458fe64714315 to your computer and use it in GitHub Desktop.
import itertools
l1=itertools.combinations("ABC",2)
print (list(l1))#Output:[('A', 'B'), ('A', 'C'), ('B', 'C')]
l1=itertools.combinations_with_replacement("ABC",2)
print (list(l1))#Output:[('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'B'), ('B', 'C'), ('C', 'C')]
l2=itertools.combinations([3,2,1],3)
print (list(l2))#Output:[(3, 2, 1)]
l2=itertools.combinations_with_replacement([3,2,1],3)
print(list(l2))#Output:[(3, 3, 3), (3, 3, 2), (3, 3, 1), (3, 2, 2), (3, 2, 1), (3, 1, 1), (2, 2, 2), (2, 2, 1), (2, 1, 1), (1, 1, 1)]
#elements are treated as unique based on their position and not by their value.
l3=itertools.combinations([1,1],2)
print (list(l3))#Output:[(1, 1)]
l3=itertools.combinations_with_replacement([1,1],2)
print (list(l3))#Output:[(1, 1), (1, 1), (1, 1)]
#since list contains only one element, given r value is 2. So it returns empty list.
l4=itertools.combinations(["ABC"],2)
print (list(l4))#Output:[]
#In combinations_with_replacement,it allows repeated element.
l4=itertools.combinations_with_replacement(["ABC"],2)
print (list(l4))#Output:[('ABC', 'ABC')]
#r value is not mentioned. It will raise TypeError
#l5=itertools.combinations([1,2,3,4])
#print (list(l5))#Output:TypeError: combinations() missing required argument 'r' (pos 2)
l5=itertools.combinations_with_replacement([1,2,3,4])
print (list(l5))#Output:TypeError: combinations_with_replacement() missing required argument 'r' (pos 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment