N个元素组合算法

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)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。