Created
July 31, 2014 05:50
-
-
Save rohit-jamuar/63cee001b4951632aad7 to your computer and use it in GitHub Desktop.
Prints all possible combinations of words from input lists; maintains order
This file contains 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
#!/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