一.排列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