N个元素组合算法
import time
def test(src,pos):
lenth = len(src)
num = len(pos)
t = -2 #用于记录取数的倒数第二个数的位置
while True:
if pos[t] == lenth + t:
if t + num == 0:
print('遍历结束')
break
t -= 1
else:
pos[t] += 1
while t < -1:
pos[t+1] = pos[t] + 1
t += 1
return pos
return False
#定义一个组合函数,参数是:源数据,组合取样个数num
def zuhe(src,num):
if num < 1:
print('元素个数输入错误')
time.sleep(5)
exit()
elif num == 1:
return list(src)
lenth = len(src) #元素长度
pos = list(range(num)) #取元素个数
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)
