N個元素組合算法
import time
def test(src,pos):
lenth = len(src)
num = len(pos)
t = -2 #用于記錄取數(shù)的倒數(shù)第二個數(shù)的位置
while True:
if pos[t] == lenth + t:
if t + num == 0:
print('遍歷結(jié)束')
break
t -= 1
else:
pos[t] += 1
while t < -1:
pos[t+1] = pos[t] + 1
t += 1
return pos
return False
#定義一個組合函數(shù)肌割,參數(shù)是:源數(shù)據(jù)踪蹬,組合取樣個數(shù)num
def zuhe(src,num):
if num < 1:
print('元素個數(shù)輸入錯誤')
time.sleep(5)
exit()
elif num == 1:
return list(src)
lenth = len(src) #元素長度
pos = list(range(num)) #取元素個數(shù)
zhlist = []
while True:
element = []
for i in pos[:-1]:
element.append(src[i]) #添加前部元素
# print(element)
tail = pos[-1]
while tail < lenth:
zhlist.append(element + [src[tail]])
tail += 1
pos = test(src,pos)
if not pos:
break
for zh in zhlist:
print(zh)
print('total: ', len(zhlist))
return zhlist
src = ['a','b','d','f','j','k']
num = 3
zuhe(src,num)