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

yipeiwu_com7年前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的全排列功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

Python实现快速多线程ping的方法

本文实例讲述了Python实现快速多线程ping的方法。分享给大家供大家参考。具体如下: #!/usr/bin/python #_*_coding:utf-8_*_ # ''' 名称...

python匹配两个短语之间的字符实例

如下所示: def ref_txt_demo(): f = open('1.txt', 'r') data = f.readlines() for line in data:...

Python threading的使用方法解析

Python threading的使用方法解析

一、 例子:我们对传参是有要求的必须传入一个元组,否则报错 import _thread as thread import time def loop1(in1): print(...

Python并发编程协程(Coroutine)之Gevent详解

Python并发编程协程(Coroutine)之Gevent详解

Gevent官网文档地址:http://www.gevent.org/contents.html 基本概念 我们通常所说的协程Coroutine其实是corporateroutine的缩...

使用Python操作Elasticsearch数据索引的教程

使用Python操作Elasticsearch数据索引的教程

Elasticsearch是一个分布式、Restful的搜索及分析服务器,Apache Solr一样,它也是基于Lucence的索引服务器,但我认为Elasticsearch对比Solr...