data=[1,2]
def pailie(data):
output=[]
# 当只有一个元素的时候排列只有一个,直接返回
if len(data)==1:
return [data]
# 当有n个元素的时候:假设除了第一个元素外,后边的n-1个元素已经拍好了,于是:
for i in data:
data_c=data.copy() #这句不是递归的步骤;这一句是复制数组的副本 ,找到后n-1个元素
data_c.remove(i)
# 这个就是递推公式了
output+=[[i]+j for j in pailie(data_c)]
return output
print(pailie(data))
# res=[[(f,g) for f,g in zip(j,range(1,len(data)+1))] for j in pailie(data)]
data=[ i for i in range(9)]
# import numpy as np
# # array=np.array([3,2,1])
# for array in pailie(data):
# array=np.array(array)
# nixushu=sum([(j>array[i+1:]).sum() for i,j in enumerate(array)])
# print(nixushu)
#===============一句话实现======比自己实现的递归快了不止8倍
from itertools import permutations
print(list(permutations(data)))
def in_l(listt,c ):
result=[]
n=len(listt)+1
for j in range(n):
b=listt.copy()
# print(b,c)
if c not in b:
b.insert(j,c)
if b not in result:
yield b
def pailie(data,listt=None):
data=[i for i in data]
if listt:
lenn=len(data)
else:
listt=[[i] for i in data]
lenn=len(data)-1
for i in range(lenn):
result=[]
for d in data:
for i in listt:
for b in in_l(i,d):
if b not in result:
result+=[b]
listt=result;
return result