Last active
August 29, 2015 14:03
-
-
Save Carolusian/009609eef5e83354f39a to your computer and use it in GitHub Desktop.
A recursive approach to combine arbitrary number of vectors, real use case: compute the combination of SKU
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
# -*- coding: utf-8 -*- | |
""" | |
The is a recusive approach solving the vectors combination problem | |
""" | |
# Y for yellow, G for green | |
# 1 2 3 4 for size | |
# H for heavy, L for light, O for overweight | |
vectors = [['Y', 'G'], | |
[1, 2, 3, 4], | |
['H', 'L', 'O']] | |
level = 0 | |
def combine(subvectors, level): | |
if len(subvectors) > 0: | |
holder = [] | |
for el in subvectors[0]: | |
print(' ' * level, "{0} + comb({1})".format(el, subvectors[1:])) | |
# el + following line | |
comb = combine(subvectors[1:], level + 1) | |
# Because we want a two dimensional result, 2d list + 2d list = 2d | |
# list | |
holder = holder + assemble(el, comb, level) | |
print(' ' * level, "Level {0}: another elem".format(level)) | |
# Only print while all variable are included, no sub-set | |
if level == 0: | |
print(holder) | |
return holder | |
else: | |
return [] | |
def assemble(el, comb, level): | |
"""assemble elem and list together | |
1 + [['H'], ['L'], ['O'] => [[1,'H'], [1, 'L'], [1, 'O'] | |
lift up, and keep it a two dimension list | |
""" | |
if len(comb) == 0: | |
# If no elem in comb, simply return the elem as list | |
return [[el]] | |
return [([el] + c) for c in comb] | |
if __name__ == "__main__": | |
# Note that a combination does not necessarily to be a combination of | |
# single elements. | |
# If can also be a single element and other vectors | |
# This the basis for recusion | |
result = combine(vectors, level) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment