用Python以字典序產生n個數的排列

來源:互聯網
上載者:User

 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]<A[i-1]:
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]<A[k]:
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)
  


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.