itertools模块中,permutations,combinations和product的使用

from itertools import permutations,combinations,product

#方法一和方法二,均实现了,输入一个字符串,输出各种排列,不考虑顺序
strs = 'abc'
#方法1
def zuHe(strs):
    n = len(strs)
    if not n:
        return strs
    lts = []
    for i in range(1,n+1):
        for j in permutations(strs,i):
            flage = True #定义一个旗帜
            for k in permutations(j):  #检查全排列中的某一种,是否已经存在于lts中,因为不考虑顺序
            # for k in permutations(j,i):  #permutations,不加参数i,默认就是全排列
                k_strs = ''.join(k)
                if k_strs in lts:
                    flage = False
                    break
            if flage:
                j_strs = ''.join(j)
                lts.append(j_strs)
    return lts


#方法2
def zuHe2(strs):
    n = len(strs)
    if not n:
        return strs
    lts = []
    for i in range(1,n+1):
        for j in combinations(strs,i):
            flage = True #定义一个旗帜
            # 检查全排列中的某一种,是否已经存在于lts中,因为不考虑顺序    combinations需要指定参数i
            for k in combinations(j,i):
                k_strs = ''.join(k)
                if k_strs in lts:
                    flage = False
                    break
            if flage:
                j_strs = ''.join(j)
                lts.append(j_strs)
    return lts

#笛卡尔,多用在组合矩阵方面
for m in product([1,2],repeat=3):
    print(m)
    
'''
(1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 2, 2)
(2, 1, 1)
(2, 1, 2)
(2, 2, 1)
(2, 2, 2)
'''
if __name__ == '__main__':
    print(zuHe(strs))  #['a', 'b', 'c', 'ab', 'ac', 'bc', 'abc']
    print(zuHe2(strs))  #['a', 'b', 'c', 'ab', 'ac', 'bc', 'abc']

猜你喜欢

转载自blog.csdn.net/qq_38839677/article/details/81949184