To generate all possible sub groups (detailed discussion)

PROBLEM - TO GENERATE ALL POSSIBLE SUB-GROUPS SUCH THAT TWO PARTS OF ORIGINAL LIST CAN BE FORMED IN WHICH
FIRST PART = SUB-GROUP
SECOND PART = ORINIGAL LIST - FIRST PART
Therefore, first part + second part = original list
(WITHOUT TAKING CARE OF DUPLICATE ITEMS)

EXAMPLE 1 - without duplicate elements
n = 5
items = [1,2,3,4,5]
POSSIBLE GROUPS = [2^(n-1)]-1 = 15
[1] , [2] , [3] , [4] , [5] , [1,2] , [1,3] , [1,4] , [1,5] , [2,3] , [2,4] , [2,5] , [3,4] , [3,5] , [4,5]

EXAMPLE 2 - with duplicate elements
n = 4
items = [4,4,7,6]
POSSIBLE GROUPS = [2^(n-1)]-1 = 7
[4] , [4] , [7] , [6] , [4,4] , [4,7] , [4,6]

# TAKE INPUT (for example n=6)
n = 6

# CREATE LIST ( l=[1,2,3,4,5,6] )
l = list(range(1,n+1))

# TOTAL POSSIBLE SUB-GROUPS for n=6, run=31
run = (2**(n-1))-1

# CREATE EMPTY LIST FOR APPENDING ITEMS OF ORIGINAL LIST TO MAKE SUB-LIST
ans = []

# CREATE EMPTY TO LIST TO COMBINE ALL SUB-LISTS
res = []

# APPEND ALL ITEMS FOR FIRST TIME AND CREATE THE FIRST SUB-LIST WHICH IS [ [1],[2],[3],[4],[5],[6] ]
for x in range(n):
    ans.append([l[x]])

# COMBINE THE FIRST SUB-LIST [ [ [1],[2],[3],[4],[5],[6] ] ]
res.append(ans)

# INITIALIZE THE INDEX OF COMBINATION LIST i.e. res TO PICK ALL SUB-LISTS ONE BY ONE AND MAKE A FLAG TO TERMINATE THE LOOP
i=0
flag = True

# START A INFINITE LOOP AND TERMINATE IT WHEN ALL POSSIBLE GROUPS ARE CREATED BY COMPARING i & run
# THIS TIME IT SHOULD ITERATE 31(run=31) times
while True:
    temp = res[i] # PICKING i-th SUB-LIST FROM COMBINATION LIST
    y = len(temp) # COMPUTE LENGTH
    ind = n - y + 1 # CALCULATE INDEX FROM WHICH ITEMS OF ORIGINAL LIST NEEDS TO BE APPENDED TO FORM SUB-LIST
    for j in range(y-1):
        ans = [] # EMPTY LIST TO CREATE SUB-LISTS
        for k in range(ind,n):
            if x>=run-1: # CHECK WHETHER ALL SUB-GROUPS ARE CREATED OR NOT
                flag = False # IF CREATED, MAKE FLAG FALSE TO TERMINATE ALL LOOPS
                break
            ans.append(temp[j]+[l[k]]) # APPEND ITEMS ONE BY ONE TO FORM SUB-LIST
            x+=1 # INCREMENT WHEN A NEW SUB-GROUP IS FORMED BY APPENDING ITEMS FROM ORIGINAL LIST TO CREATE SUB-LIST
        if flag == False: # LOOP TERMINATION
            break
        res.append(ans) # COMBINE THE CREATED SUB-LIST
        ind+=1 # INCREMENT INDEX FROM WHICH ITEMS OF ORIGINAL LIST NEEDS TO BE APPENDED TO FORM SUB-LIST
    i+=1 # INCREMENT INDEX TO PICK NEXT SUB-LIST FROM COMBINATION LIST
    if flag == False: # LOOP TERMINATION
        break

# CREATE EMPTY LIST TO ARRANGE ALL SUB-GROUPS COLLECTED INTO COMBINATION LIST
final = []
for i in res: # PICK SUB-LISTS ONE BY ONE
    for j in i: # PICK SUB-GROUPS STORED IN THAT SUB-LISTS
        final.append(j) # ADD SUB-GROUPS TO FINAL ARRANGEMENT

print(' N =',n)
print(' Original List =',l)
print(' Possible Sub Groups =',run)

#PRINT ALL SUB-GROUPS
for i in final:
    print(i)

Comments