Skip to content

Instantly share code, notes, and snippets.

@jmquintana79
Last active October 2, 2017 01:09
Show Gist options
  • Save jmquintana79/d64c7b501b7d8bd60e3e to your computer and use it in GitHub Desktop.
Save jmquintana79/d64c7b501b7d8bd60e3e to your computer and use it in GitHub Desktop.
combinatorics with "itertools" library
import itertools
lx = ["1","2","3","4"]
# combinations
print( "Combiantions: %s"%list(itertools.combinations(lx,r=2)) )
# permutations
print( "Permutations: %s"%list(itertools.permutations(lx,r=2)) )
# product
print( "Permutations with replacement (product): %s"%list(itertools.product(lx,repeat=2)) )
# combinations with replacement
print( "Combinations with replacement: %s"%list(itertools.combinations_with_replacement(lx,r=2)) )
# combinations without replacement
print( "Combinations without replacement: %s"%list(itertools.combinations(lx,r=2)) )
#Combiantions: [('1', '2'), ('1', '3'), ('1', '4'), ('2', '3'), ('2', '4'), ('3', '4')]
#Permutations: [('1', '2'), ('1', '3'), ('1', '4'), ('2', '1'), ('2', '3'), ('2', '4'), ('3', '1'), ('3', '2'), ('3', '4'), ('4', '1'), ('4', '2'), ('4', '3')]
#Permutations with replacement (product): [('1', '1'), ('1', '2'), ('1', '3'), ('1', '4'), ('2', '1'), ('2', '2'), ('2', '3'), ('2', '4'), ('3', '1'), ('3', '2'), ('3', '3'), ('3', '4'), ('4', '1'), ('4', '2'), ('4', '3'), ('4', '4')]
#Combinations with replacement: [('1', '1'), ('1', '2'), ('1', '3'), ('1', '4'), ('2', '2'), ('2', '3'), ('2', '4'), ('3', '3'), ('3', '4'), ('4', '4')]
#Combinations without replacement: [('1', '2'), ('1', '3'), ('2', '3')]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment