Created
March 5, 2020 21:57
-
-
Save psaia/80d8d7c2dc0ab392a2a3100ea56794f3 to your computer and use it in GitHub Desktop.
combinator.py
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
FRUIT = "fruit" | |
VEGGIE = "veggie" | |
class Product: | |
def __init__(self, name, kind): | |
self.name = name | |
self.kind = kind | |
def __repr__(self): | |
return "(name: %s / kind: %s)" % (self.name, self.kind) | |
# Collection of all products. | |
products = [ | |
Product("apple", FRUIT), | |
Product("tangerine", FRUIT), | |
Product("grape", FRUIT), | |
Product("cucumber", VEGGIE), | |
Product("sweet pea", VEGGIE), | |
Product("celary", VEGGIE), | |
Product("tomato", VEGGIE), | |
] | |
# Tuples of templates and tags that they implement. | |
templates = [ | |
["i love {{fruit}}", [FRUIT]], | |
["i love {{fruit}} but only {{fruit}}", [FRUIT, FRUIT]], | |
["i love {{fruit}} and sometimes {{veggie}}", [FRUIT, VEGGIE]], | |
] | |
# Create dictionary of products by type. | |
templateDict = { | |
FRUIT: list(filter(lambda p: p.kind == FRUIT, products)), | |
VEGGIE: list(filter(lambda p: p.kind == VEGGIE, products)), | |
} | |
def combinator(arr): | |
n = len(arr) | |
indices = [0 for i in range(n)] | |
combset = [] | |
while (1): | |
combs = [] | |
for i in range(n): | |
combs.append(arr[i][indices[i]]) | |
combset.append(combs) | |
next = n - 1 | |
while (next >= 0 and (indices[next] + 1 >= len(arr[next]))): | |
next-=1 | |
if (next < 0): | |
return combset | |
indices[next] += 1 | |
for i in range(next + 1, n): | |
indices[i] = 0 | |
return combset | |
for tpl in templates: | |
columns = [] | |
for type in tpl[1]: | |
productsForColumn = templateDict[type] | |
columns.append(templateDict[type]) | |
for col in combinator(columns): | |
print(tpl[0] + " - " + "".join(map(repr, col))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment