我希望你能帮助我,我想从以下列表列表中生成组合(作为 nxn 矩阵工作):
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
但我需要,如果我取第一个列表的第一个数字,然后作为矩阵运算,删除列的其他元素和所选元素的行,然后生成可能的组合
例如,我在第一个列表中选择 1,那么唯一可能生成的组合是:(1,5,9) 和 (1,8,6),因为消除了行和列。
我正在尝试构建一个递归函数来通过删除列和行来实现这一点,问题是我不确定如何使用组合构建列表。
这是我到目前为止:
list = []
def combinations(matrix):
matrix_rows = len(matrix)
if matrix_rows == 0:
# Base case
return matrix
else:
# Recursive case
# Always select first row
seq = []
for index, a in enumerate(matrix[0]):
E = a
seq.append(E)
# Remove i from row of index element a
new_matrix = remove_row(matrix, 0)
# Remove j from column index of element a
new_matrix = remove_column(new_matrix, index)
# Call again with new matrix
combinations(new_matrix)
list.append(seq)
return list
def remove_row(original_matrix, element_row_index):
new_matrix = []
if (len(original_matrix)) >= element_row_index:
new_matrix = original_matrix[:]
new_matrix.remove(original_matrix[element_row_index])
return new_matrix
def remove_column(matrix, index):
return [(x[0:index] + x[index + 1:]) for x in matrix]
使用上面的矩阵,我希望有:
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
print("Result: ", combinations(A))
Result: [[1,5,9], [1,6,8], [2,4,9], [2,6,7], [3,4,8], [3,5,7]]
任何人都可以帮助我吗?或者给我一个更好的方法的建议
补充:一个 4x4 的例子:
A = [[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]
Results: [1,6,11,16], [1,6,12,15],[1,7,10,16], [1,7,12,14], [1,8,10, 15], [1,8,11, 14], ....