Python 基礎 排列組合的實現
阿新 • • 發佈:2018-11-08
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow
也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!
考慮這樣一個問題,給定一個矩陣(多維陣列,numpy.ndarray()
),如何shuffle
這個矩陣(也就是對其行進行全排列),如何隨機地選擇其中的k
涉及的函式主要有:
np.random.permutation()
itertools.combinations()
itertools.permutations()
# 1. 對0-5之間的數進行一次全排列>>>np.random.permutation(6)array([3, 1, 5, 4, 0, 2])# 2. 建立待排矩陣>>>A = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] )# 3. shuffle矩陣A>>>p = np.random.permutation(A.shape[0])>>>parray([1, 2, 0])>>>A[p, :] array([[ 5, 6, 7, 8], [ 9, 10, 11, 12], [ 1, 2, 3, 4]] )
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
C25的實現
>>>from itertools import permutations>>>pertumations(range(5), 2)<itertools.permutations object at 0x0233E360>>>>perms = permutations(range(5), 2)>>>perms[(0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 2), (1, 3), (1, 4), (2, 0), (2, 1), (2, 3), (2, 4), (3, 0), (3, 1), (3, 2), (3, 4), (4, 0), (4, 1), (4, 2), (4, 3)]>>>len(perms)20
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
# 5. 任取其中的k(k=2)行>>>c = [c for c in combinations(range(A.shape[0]), 2)]>>>A[c[0], :] # 一種排列array([[1, 2, 3, 4], [5, 6, 7, 8]])
- 1
- 2
- 3
- 4
- 5