用Python以字典序生成n个数的排列

 1 #!/usr/bin/python
2 #coding:utf-8
3 def next_permutation(A):

4 '''
5 input: array of a permutation of n numbers
6 output: the next permutation
7 Algorithm: dicttionary order
8
'''

9 #print(A)
10 n = len(A)

11 last = n - 1
12 i = last
13 while i>0 and A[i]
14 i -= 1
15 if i==0:
16 return False
17 k = i
18 j = last
19 while j >= i:
20 if A[j]>A[i-1] and A[j]
21 k = j
22 j -= 1
23 A[k],A[i-1] = A[i-1],A[k]
24 A[i:] = A[i:][::-1]
25 return True
26
27 def permutation(n):
28 '''
29 Input: int num n
30 Output: permutation of the n number from small to big
31
'''

32 B = []
33 A = list(range(1,n+1))
34 B.append(A[::])
35 flag = next_permutation(A)
36 B.append(A[::])
37 while flag:
38 flag = next_permutation(A)
39 B.append(A[::])
40
41 return B
42
43 AA = permutation(4)
44 for i in AA:
45 print(i)
  


转载于:https://www.cnblogs.com/wangshide/archive/2011/10/01/2197115.html

你可能感兴趣的:(用Python以字典序生成n个数的排列)