Skip to content

Instantly share code, notes, and snippets.

@tbnorth
Created April 3, 2017 18:55
Show Gist options
  • Save tbnorth/92f24973a9d12c3396c84f2c07869ef8 to your computer and use it in GitHub Desktop.
Save tbnorth/92f24973a9d12c3396c84f2c07869ef8 to your computer and use it in GitHub Desktop.
Cross factor generator
"""
cross_factor.py - describe
Terry N. Brown, [email protected], Mon Apr 03 13:28:41 2017
"""
from collections import namedtuple
def cross_factor(lists):
"""Return (as namedtuples) all combinations of elements from dict of lists"""
keys = lists.keys()
Record = namedtuple("Record", keys + ['r_pos', 'r_len'])
pos = [0] * len(keys)
lengths = [len(lists[k]) for k in keys]
while True:
values = {k:lists[k][pos[n]] for n, k in enumerate(keys)}
values.update({'r_pos': pos, 'r_len': lengths})
yield Record(**values)
i = len(keys)-1
pos[i] += 1
if pos[i] == lengths[i]:
while pos[i] == lengths[i] and i > 0:
pos[i] = 0
i -= 1
pos[i] += 1
if pos[i] < lengths[i]:
break
else:
return
def main():
for i in cross_factor({'ltr': 'AB', 'num': [1,2,[3,4]], 'type': (str, int)}):
print i
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment