所以假設我的矩陣看起來像這樣(總是一個正方形):
a1 a2 a3
b1 b2 b3
c1 c2 c3
我想讓方格中的元素(a1, a2, b1, b2), (a2, a3, b2, b3),etc不相似——意思是 : a1 != a2 != b1 != b2。
我有這個用于遞回生成矩陣的代碼:
def generate(elements):
if not elements:
return (),
final = []
for items in generate(elements[:-1]):
for item in elements[-1]:
final.append(items (item,))
return final
def product(*args, repeat=1):
pools = [list(pool) for pool in args] * repeat
return list(generate(pools))
def main():
D = 3
combinations = product([0, 128, 196], repeat=D)
matrices = product(combinations, repeat=D)
return matrices
這里elements是一個整數串列(數目不詳),假設[0, 128, 196]和repeat是方陣的大小。
我希望函式中的某個地方應用該規則,以便它僅根據我提到的規則生成矩陣。
所以最終的最終結果將是 3x3 矩陣的所有可能變化,但應用了該規則。
寧愿在不匯入熊貓或類似的東西的情況下做到這一點。
uj5u.com熱心網友回復:
這是一種可能性:
- 使用
itertools.permutations和生成所有可能的矩陣numpy.reshape; - 檢查矩陣是否適合
numpy.diff用于測驗相等的相鄰元素。
from more_itertools import distinct_permutations
from numpy import array, diff, count_nonzero
def check_matrix(m):
d_vert = diff(m, axis=0) # vertically adjacent
if count_nonzero(d_vert) < d_vert.size:
return False
d_hori = diff(m, axis=1) # horizontally adjacent
if count_nonzero(d_hori) < d_hori.size:
return False
d_dia1 = d_vert[:,:-1] d_hori[1:,:] # northwest-southeast diagonally adjacent
if count_nonzero(d_dia1) < d_dia1.size:
return False
d_dia2 = d_hori[:-1,:] - d_vert[:,:-1] # southwest-northeast diagonally adjacent
return count_nonzero(d_dia2) == d_dia2.size
def gen_matrices(h,w, elements):
for p in distinct_permutations(elements, h*w):
m = array(p).reshape((h,w))
if check_matrix(m):
yield m
for m in gen_matrices(2, 3, [1,2,3,4,1,2]): # should be 8 results with 3 and 4 in the middle column
print(m)
# [[1 3 1]
# [2 4 2]]
# [[1 3 2]
# [2 4 1]]
# [[1 4 1]
# [2 3 2]]
# [[1 4 2]
# [2 3 1]]
# [[2 3 1]
# [1 4 2]]
# [[2 3 2]
# [1 4 1]]
# [[2 4 1]
# [1 3 2]]
# [[2 4 2]
# [1 3 1]]
檔案:
- numpy.diff
- numpy.reshape
- numpy.count_nonzero
- numpy.size
- itertools.permutations
- more_itertools.distinct_permutations
uj5u.com熱心網友回復:
通過添加一個檢查每 2 行的新函式來解決它。有點慢,但它的作業原理。
def square_chec(row1, row2):
if row1[-1] == row2[-1]:
return False
for num in range(len(row1)-1):
if row2[num 1] == row1[num] or row2[num] == row1[num] or row1[num 1] == row2[num] or row2[num] == row1[num]:
return False
return True
def generate(elements):
if not elements:
return (),
final = []
for items in generate(elements[:-1]):
for item in elements[-1]:
if items:
if items[-1] != item:
if type(item) == tuple:
if square_chec(items[-1], item):
final.append(items (item,))
else:
final.append(items (item,))
else:
final.append(items (item,))
return final
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/392910.html
