python | 排列与组合

一.排列permutations

在Python中,permutations 函数是 itertools 模块提供的一个方法,用于生成输入可迭代对象的全排列。排列是一系列元素的有序列表,其中元素的顺序很重要。

from itertools import permutations
item = [1, 2, 3, 4, 5, 6, 7, 8]
# 获取全排列
x = list(permutations(item))
# print(x)
print(len(x))
# 输出40320

如果只是要选取部分进行排列,则修改代码中dfs的结束条件即可

a = [1, 2, 3, 4, 5, 6, 7, 8]
# 生成从第s个数到第t个数的全排列
num = 0
def swap(x, b):
    t = x
    x = b
    b = t
    return x, b
def dfs(s, t):
    global num
    if s == 3:  # 修改此处
        num += 1
        return
    for i in range(s, t + 1):
        a[s], a[i] = swap(a[i], a[s])
        dfs(s + 1, t)
        a[s], a[i] = swap(a[i], a[s])
dfs(0, 7)
print(num)
# 输出336

二.使用dfs进行排列

a = [1, 2, 3, 4, 5, 6, 7, 8]
# 生成从第s个数到第t个数的全排列
num = 0
def swap(x, b):
    t = x
    x = b
    b = t
    return x, b
def dfs(s, t):
    global num
    if s == t:
        num += 1
        return
    for i in range(s, t + 1):
        a[s], a[i] = swap(a[i], a[s])
        dfs(s + 1, t)
        a[s], a[i] = swap(a[i], a[s])
dfs(0, 7)
print(num)

三.组合combinations

from itertools import combinations
item = [1, 2, 3, 4, 5, 6, 7, 8]
x = list(combinations(item, 8))
print(len(x))
# 输出1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值