Skip to content

Instantly share code, notes, and snippets.

@gregglind
Created February 8, 2012 23:25
Show Gist options
  • Save gregglind/1775372 to your computer and use it in GitHub Desktop.
Save gregglind/1775372 to your computer and use it in GitHub Desktop.
Recursive python "product"
"""
this has a lot of list / tuple casting, and doesn't use
native python list properties to full advantage.
It mimics Little Schemer style coding quite well though.
"""
import itertools
def produit(*lists):
""" generator of full outer product over all lists
>>> lists = [[1,2,3],[4,5],[6,7]]
>>> a = list(produit(*lists))
>>> b = list(itertools.product(*lists))
>>> len(a), len(b)
(12, 12)
>>> sorted(a) == sorted(b)
True
"""
if lists:
L, rest = lists[0],lists[1:]
for x in L:
for y in produit(*rest):
yield tuple([x] + list(y))
else:
yield []
"""
if len(lists) == 1:
for x in lists[0]:
yield [x,]
else:
for x in lists[0]:
for y in produit(*lists[1:]):
yield tuple([x] + list(y))
"""
"""
[1,2,3],[4,5,6],[7,8]
for each x in something([4,5,6],[7,8]):
yield [1] + x
1 + something([4,5,6]
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment