Created
March 4, 2010 19:35
-
-
Save voyeg3r/322039 to your computer and use it in GitHub Desktop.
iterações com a biblioteca itertools
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # First, import itertools: | |
| # source: http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python | |
| import itertools | |
| # Permutation: | |
| print list(itertools.permutations([1,2,3,4], 2)) | |
| [(1, 2), (1, 3), (1, 4), | |
| (2, 1), (2, 3), (2, 4), | |
| (3, 1), (3, 2), (3, 4), | |
| (4, 1), (4, 2), (4, 3)] | |
| # Combination (order matters): | |
| print list(itertools.combinations('123', 2)) | |
| [('1', '2'), ('1', '3'), ('2', '3')] | |
| #Cartesian product (with several iterables): | |
| print list(itertools.product([1,2,3], [4,5,6])) | |
| [(1, 4), (1, 5), (1, 6), | |
| (2, 4), (2, 5), (2, 6), | |
| (3, 4), (3, 5), (3, 6)] | |
| #Cartesian product (with one iterable and itself): | |
| print list(itertools.product([1,2], repeat=3)) | |
| [(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2), | |
| (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment