Skip to content

Instantly share code, notes, and snippets.

@hughdbrown
Created December 10, 2015 17:00
Show Gist options
  • Select an option

  • Save hughdbrown/32826cd2408ecdc422b5 to your computer and use it in GitHub Desktop.

Select an option

Save hughdbrown/32826cd2408ecdc422b5 to your computer and use it in GitHub Desktop.
Generator for cartesian product
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