Created
December 10, 2015 17:00
-
-
Save hughdbrown/32826cd2408ecdc422b5 to your computer and use it in GitHub Desktop.
Generator for cartesian product
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
| def cartesian(lol): | |
| if not lol: | |
| yield [] | |
| else: | |
| left, right = lol[0], lol[1:] | |
| for item in left: | |
| for result in cartesian(right): | |
| yield [item] + result | |
| >>> data = [ | |
| ... [1, 2, 3], | |
| ... [4, 5], | |
| ... [6, 7, 8], | |
| ... ] | |
| >>> print(list(cartesian(data))) | |
| [[1, 4, 6], [1, 4, 7], [1, 4, 8], [1, 5, 6], [1, 5, 7], [1, 5, 8], [2, 4, 6], [2, 4, 7], [2, 4, 8], [2, 5, 6], [2, 5, 7], [2, 5, 8], [3, 4, 6], [3, 4, 7], [3, 4, 8], [3, 5, 6], [3, 5, 7], [3, 5, 8]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment