打印数组所有排列 python

本人.net一名,最近在看数据结构与算法分析,中间涉及的一些比较有意思的算法题,打算用python实现以下。选择python的原因,就是想熟悉一下python的语法,和pycharm基本的应用。

本篇,算法为:打印数组的所有排列可能。废话不多说,直接上代码。

 1 #自动生成list
 2 def creataList(n):
 3     numlist=[];
 4     for i in range(n):
 5         numlist.append(i);
 6 
 7     return numlist;
 8 #copy list排除某一个元素
 9 def copewithout(lst,index):
10     newlst=[];
11     for i in range(len(lst)):
12         if(i==index):
13             continue;
14         newlst.append(lst[i]);
15     return newlst;
16 
17 #打印所有排列
18 def printallchildlist(numlist,index,printlist,length):
19     if(index==length-1):
20         printlist[index]=numlist[0];
21         print(printlist);
22     else:
23         for i in range(len(numlist)):
24             printlist[index]=numlist[i];
25             newnumlst=copewithout(numlist,i);
26             printallchildlist(newnumlst,index+1,printlist,length);
27 #主函数
28 def domain(num):
29     numlst=creataList(num);
30     printlst=creataList(num);
31     printallchildlist(numlst,0,printlst,num);
32 
33 domain(3);

这是测试结果:

D:\Learning\Python\Test\venv\Scripts\python.exe D:/Learning/Python/Test/2.13.py
[0, 1, 2]
[0, 2, 1]
[1, 0, 2]
[1, 2, 0]
[2, 0, 1]
[2, 1, 0]

  

猜你喜欢

转载自www.cnblogs.com/answerme/p/9302356.html
今日推荐