[範例] next_permutation

看板Python作者 (To littlepig with love)時間11年前 (2014/05/29 10:57), 11年前編輯推噓2(203)
留言5則, 4人參與, 最新討論串1/1
def next_permutation(L): n = len(L) if n == 0 or n == 1: return (False, L) i = n - 1 while True: i -= 1 if L[i] < L[i+1]: j = n - 1 while not ( L[i] < L[j] ): j = j - 1 L[i], L[j] = L[j], L[i] nL = L[(i+1):] nL.reverse() L[(i+1):] = nL return (True, L) if i == 0: L.reverse() return (False, L) 執行範例: >>> L1 = [ 1, 2, 3, 4 ] >>> count = 0 >>> not_yet = True >>> while not_yet: count += 1 print("%5d" % count, L1) (not_yet, L1) = next_permutation(L1) 1 [1, 2, 3, 4] 2 [1, 2, 4, 3] 3 [1, 3, 2, 4] 4 [1, 3, 4, 2] 5 [1, 4, 2, 3] 6 [1, 4, 3, 2] 7 [2, 1, 3, 4] 8 [2, 1, 4, 3] 9 [2, 3, 1, 4] 10 [2, 3, 4, 1] 11 [2, 4, 1, 3] 12 [2, 4, 3, 1] 13 [3, 1, 2, 4] 14 [3, 1, 4, 2] 15 [3, 2, 1, 4] 16 [3, 2, 4, 1] 17 [3, 4, 1, 2] 18 [3, 4, 2, 1] 19 [4, 1, 2, 3] 20 [4, 1, 3, 2] 21 [4, 2, 1, 3] 22 [4, 2, 3, 1] 23 [4, 3, 1, 2] 24 [4, 3, 2, 1] >>> -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.169.131.239 ※ 文章網址: http://www.ptt.cc/bbs/Python/M.1401332253.A.A92.html ※ 編輯: bigpigbigpig (1.169.131.239), 05/29/2014 12:47:30

05/29 13:04, , 1F
itertool表示
05/29 13:04, 1F

05/29 17:32, , 2F
這是要實作離散數學中的作法吧XD
05/29 17:32, 2F

05/30 09:58, , 3F
so..? C++STL都有, 還有prev_permutation, 實做這個
05/30 09:58, 3F

05/30 09:58, , 4F
要做啥?
05/30 09:58, 4F

05/30 14:58, , 5F
試試 L = [ 0, 0, 1, 1, 1 ] :)
05/30 14:58, 5F
文章代碼(AID): #1JXg8TgI (Python)
文章代碼(AID): #1JXg8TgI (Python)