Skip to content

Instantly share code, notes, and snippets.

@wildonion
Last active October 28, 2020 11:50
Show Gist options
  • Save wildonion/dda42cffbbe8414c24b5e4f1240f9926 to your computer and use it in GitHub Desktop.
Save wildonion/dda42cffbbe8414c24b5e4f1240f9926 to your computer and use it in GitHub Desktop.
all possible subset combinations of a set
# =====================================
# calculate all possible subset for a set
# base prespective for n nested loop and other dynamic problems!
# for i in [0..2]:
# for j in [0..2]:
# for p in [0..2]:
# for q in [0..2]:
# 0 0 0 0 -> 0 0 0 2 -> 0 0 1 0 -> 0 0 1 2
# 0000, 0001, 0002, 0010, 0011, 0012, 0020, ..., 2222, (1)0000
# i j p q ...n ta...
# i1 i2 i3 ... in
# setlst = [[0,1,2], [0,1,2], [0,1,2]]
setlst = [["cs","wo","force", "shi"], ["cs","wo","force", "shi"], ["cs","wo","force", "shi"]]
n = len(setlst)
k = len(setlst[0])
idx = 0
lst = []
# METHOD 1
def select():
global setlst, lst, idx
lst = []
t = idx
for i in range(n):
lst.append(setlst[i][t%k])
t = t//k
idx += 1
return idx != n**k+1
while select():
print(lst, "=>" , idx, ''.join(str(i) for i in lst))
# METHOD 2
i = [0 for _ in range(0,n)]
def finished():
global i
for j in i:
if j is not 0:
return False
return True
def check():
global i, k, n
for j in range(len(i)):
if i[j] >= k:
i[j] = 0
if j+1 < n:
i[j+1] += 1
def inc():
global i
i[0] += 1
check()
def select():
global setlst, i, n, k
tmp = []
for j in range(len(i)):
yield setlst[j][i[j]]
print([m for m in select()])
inc()
while not finished():
print([m for m in select()])
inc()
# METHOD 3
def com(lst):
N = len(lst)
for i in range(2**N):
combo = []
for j in range(N):
if (i >> j) % 2 == 1:
combo.append(lst[j])
print(lst[j])
yield combo
for i in com([1,2,3,5]):
print(i, ", ", end="")
# METHOD 4 : TODO: fix the bugs and make it faster!!!!!! use multi processing using some AI algo
import copy
lst = [ [1,2,3], [4,5,6], [7,8,9] ]
y, combo, lt = [], [], copy.deepcopy(lst)
def firstElem(lst):
if len(lst)>0:
lst.remove(lst[0])
return lst
else:
return
def allCombo(lst):
global y, combo
if len(lst)>0:
a = lst[0][0]
while a is not None:
y.append(a)
allCombo(firstElem(lst))
lt[0].remove(a)
a = lt[0][0]
lt.remove(lt[0])
allCombo(lt)
else:
combo.append(y)
return combo
print(allCombo(lst))
# =====================================
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment