python3 排列组合

运行环境 : python 3.6.0

 

一 、python 自身内置就有这种工具 ,模块名为 itemtools 。

所有结果 :

# -*- encoding=utf-8 -*-
from itertools import product

test_data = list('234')

""" 所有结果 """
for item in product(test_data, repeat=2):
    print(item)

# 输出
"""
('2', '2')
('2', '3')
('2', '4')
('3', '2')
('3', '3')
('3', '4')
('4', '2')
('4', '3')
('4', '4')
"""

 

排列 :

# -*- encoding=utf-8 -*-
from itertools import permutations

test_data = list('234')

""" 排列 """
for item in permutations(test_data, 2):
    print(item)

# 输出
"""
('2', '3')
('2', '4')
('3', '2')
('3', '4')
('4', '2')
('4', '3')
"""

 

组合 :

# -*- encoding=utf-8 -*-
from itertools import combinations

test_data = list('1234')

""" 组合 """
for item in combinations(test_data, 3):
    print(item)


# 输出
"""
('1', '2', '3')
('1', '2', '4')
('1', '3', '4')
('2', '3', '4')
"""

 

有替换的组合 :

# -*- encoding=utf-8 -*-
from itertools import combinations_with_replacement

test_data = list('234')

""" 有替换的组合 """
for item in combinations_with_replacement(test_data, 2):
    print(item)

# 输出
"""
('2', '2')
('2', '3')
('2', '4')
('3', '3')
('3', '4')
('4', '4')
"""

二 、自己设计算法也可以实现排列组合效果

组合 :

import copy  # 实现list的深复制


def combine(lst, k):
    """ lst: 数组  k: 组合长度  return: 组合 """
    result = []
    tmp = [0] * k
    length = len(lst)

    def next_num(Li=0, Ni=0):
        if Ni == k:
            result.append(copy.copy(tmp))
            return
        for Lj in range(Li, length):
            tmp[Ni] = lst[Lj]
            next_num(Lj + 1, Ni + 1)

    next_num()
    return result


if __name__ == '__main__':
    lst = list('2346')
    for item in combine(lst, 3):
        print(item)

 

你可能感兴趣的:(Python)