Skip to content

Instantly share code, notes, and snippets.

@rohit-jamuar
Created July 31, 2014 05:50
Show Gist options
  • Save rohit-jamuar/63cee001b4951632aad7 to your computer and use it in GitHub Desktop.
Save rohit-jamuar/63cee001b4951632aad7 to your computer and use it in GitHub Desktop.
Prints all possible combinations of words from input lists; maintains order
#!/usr/bin/python
from itertools import product
def set_combination(list_of_lists):
'''
Prints out all possible combinations of words (each combination only once),
where one word is taken from each list, in the same order the lists are
given.
'''
if type(list_of_lists) == list:
for item in list_of_lists:
if type(item) != list:
raise GeneratorExit
temp = set()
for elem in product(*list_of_lists):
if elem not in temp:
temp.add(elem)
yield ' '.join(elem)
else:
raise GeneratorExit
if __name__ == '__main__':
LIST_OF_ITEMS = [['apple', 'banana', 'pear'], ['car', 'truck'],
['zambia', 'malawi', 'kenya']]
try:
for combination_string in set_combination(LIST_OF_ITEMS):
print combination_string
except GeneratorExit:
print "The argument should be a list of lists!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment