网络编程
位置:首页>> 网络编程>> Python编程>> Python循环实现n的全排列功能

Python循环实现n的全排列功能

作者:wuhen_n  发布时间:2022-08-15 21:04:08 

标签:Python,循环,全排列

描述:

输入一个大于0的整数n,输出1到n的全排列:

例如:


n=3,输出[[3, 2, 1], [2, 3, 1], [2, 1, 3], [3, 1, 2], [1, 3, 2], [1, 2, 3]]
n=4,输出[[4, 3, 2, 1], [3, 4, 2, 1], [3, 2, 4, 1], [3, 2, 1, 4], [4, 2, 3, 1], [2, 4, 3, 1], [2, 3, 4, 1], [2, 3, 1, 4], [4, 2, 1, 3],
[2, 4, 1, 3], [2, 1, 4, 3], [2, 1, 3, 4], [4, 3, 1, 2], [3, 4, 1, 2], [3, 1, 4, 2], [3, 1, 2, 4], [4, 1, 3, 2], [1, 4, 3, 2],
[1, 3, 4, 2], [1, 3, 2, 4], [4, 1, 2, 3], [1, 4, 2, 3], [1, 2, 4, 3], [1, 2, 3, 4]]

思路:


为1时,结果为1
为2时,结果就是两种:1,2 2,1(1的前后插入)
为3时,结果就是六种:1,2,3 1,3,2 3,2,1 (1,2的前中后插入)
3,2,1 2,3,1 2,1,3 (2,1的前中后插入)

代码:


import copy
def full_arrange(n):
 data = [] # 中间结果
 res = [] # 最终结果
 if n == 1 :
   return 1
 res = [[1]]
 for i in range(2, n+1):
   for j in range(len(res)): # 遍历res数组(二维数组)
     for x in range(len(res[j])+1): # 遍历res数组中的元素(一维数组)
       data = copy.copy(res[j]) # 浅拷贝
       data.insert(x,i) # 在一维数组的不同位置插入元素,获得新的数组
       res.append(data)
       x += 1
     j += 1
   # 删除多余数组(原始数组) 最后保留的数据(一维数组的长度) == i
   while True:
     if len(res[0]) != i:
       res.remove(res[0])
     else:
       break
   i += 1
 return res
print(full_arrange(n))

总结

以上所述是小编给大家介绍的Python循环实现n的全排列功能,网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

来源:https://blog.csdn.net/wuhen_n/article/details/98511553

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com