Last active
November 29, 2018 03:14
-
-
Save imran31415/18ed73f1737b0f7b34dafd7f2ad6ec8f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#python 2.7+, 3 | |
def get_subsets_recursive(l, c=0): | |
""" | |
Recursivemethod | |
l is the set of items to get all combination subsets | |
c is to track recursion depth for visibility | |
""" | |
c+=1 | |
#end recursion loop once at the end of the list | |
if not l: | |
return [[]] | |
#recursively call get_subsets deducting the first item on each successive call | |
sublists = get_subsets_recursive(l[1:], c) | |
print(("Recursion depth: {}".format(c))) | |
print(("Current sublists", sublists)) | |
#sublist_output will be the new combinations added to the master set (l) | |
sublist_output = [] | |
#for each item in the set, | |
for item in sublists: | |
new_combo = [l[0]] + item | |
print ("New Combination created: ") | |
print(new_combo) | |
sublist_output.append(new_combo) | |
print ("Output Updated: ") | |
print(sublist_output) | |
print(('Finished calculating recursion: {}'.format(c))) | |
print(('Finished recursion output: {}'.format(sublists+sublist_output))) | |
return sublists + sublist_output | |
def get_subsets_for_loop(l): | |
""" | |
go through each item and create a tmp list for that item | |
for each item on | |
""" | |
output_sets = [[]] | |
for i,x in enumerate(l): | |
#this will store the set of new combinations created with the new item combined with all previously created combinations | |
t= [] | |
#for each item in the exisiting output set combine it with the new item | |
for v,c in enumerate(output_sets): | |
t.append(c + [x]) | |
#append all new combinations to master list | |
output_sets+=(t) | |
return output_sets | |
r = get_subsets_recursive([1,2,3,4,5]) | |
f = get_subsets_for_loop([1,2,3,4,5]) | |
print('Recursive output: ') | |
print (r) | |
""" | |
[[], [5], [4], [4, 5], [3], [3, 5], [3, 4], [3, 4, 5], [2], [2, 5], [2, 4], [2, 4, 5], [2, 3], [2, 3, 5], [2, 3, 4], [2, 3, 4, 5], [1], [1, 5], [1, 4], [1, 4, 5], [1, 3], [1, 3, 5], [1, 3, 4], [1, 3, 4, 5], [1, 2], [1, 2, 5], [1, 2, 4], [1, 2, 4, 5], [1, 2, 3], [1, 2, 3, 5], [1, 2, 3, 4], [1, 2, 3, 4, 5]] | |
""" | |
print('forloop output: ') | |
""" | |
[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3], [4], [1, 4], [2, 4], [1, 2, 4], [3, 4], [1, 3, 4], [2, 3, 4], [1, 2, 3, 4], [5], [1, 5], [2, 5], [1, 2, 5], [3, 5], [1, 3, 5], [2, 3, 5], [1, 2, 3, 5], [4, 5], [1, 4, 5], [2, 4, 5], [1, 2, 4, 5], [3, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5], [1, 2, 3, 4, 5]] | |
""" | |
print (f) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment