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)

 

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中有多种方式可以求排列组合,下面介绍两种常见的方法。 1. 使用itertools模块 Python的itertools模块提供了多种排列组合的函数,包括permutations(排列)和combinations(组合)。这些函数可以快速方便地生成排列组合结果。 例如,要求长度为3的列表[1,2,3]的所有排列,可以使用itertools.permutations函数: ```python import itertools lst = [1,2,3] perms = itertools.permutations(lst, 3) for perm in perms: print(perm) ``` 输出结果为: ``` (1, 2, 3) (1, 3, 2) (2, 1, 3) (2, 3, 1) (3, 1, 2) (3, 2, 1) ``` 要求长度为2的列表[1,2,3]的所有组合,可以使用itertools.combinations函数: ```python import itertools lst = [1,2,3] combs = itertools.combinations(lst, 2) for comb in combs: print(comb) ``` 输出结果为: ``` (1, 2) (1, 3) (2, 3) ``` 2. 自己实现排列组合函数 如果不想使用itertools模块,也可以自己实现排列组合函数。下面是一个简单的实现: ```python def permutations(lst, n): if n == 0: yield [] else: for i in range(len(lst)): for perm in permutations(lst[:i] + lst[i+1:], n-1): yield [lst[i]] + perm def combinations(lst, n): if n == 0: yield [] else: for i in range(len(lst)-n+1): for comb in combinations(lst[i+1:], n-1): yield [lst[i]] + comb ``` 这里的permutations函数和combinations函数分别实现了排列和组合。它们都使用了递归算法,对于每个元素,可以选择使用或者不使用。当选择了n个元素后,即得到一个排列或组合。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值