如何使用 Julia(或 Python)从非方形矩阵中获取所有(对角线)线

问题描述 投票:0回答:1

我需要从矩阵中获取所有对角线。 下面的代码仅适用于方阵(如 3x3、4x4、...),但不适用于非方阵(如 3x4、4x3、...)。

有什么建议如何解决 3x4、3x5、4x7 ... 等矩阵的问题吗?

function get_lines(M::Matrix{Int64})

    nrows = size(M, 1)
    ncols = size(M, 2)

    @assert nrows == ncols "Matrix in not square (number of rows and columns are not equal)"
    
    h = [Int64[] for _ in 1:ncols] # horizontals
    v = [Int64[] for _ in 1:nrows] # verticals
    f = [Int64[] for _ in 1:(ncols + nrows - 1)] # forward diagonals
    b = [Int64[] for _ in 1:(ncols + nrows - 1)] # backward diagonals

    for x in 1:ncols 
        for y in 1:nrows
            push!(h[y], M[y, x])
            push!(v[x], M[y, x])
            push!(f[x+y-1], M[y, x])
            push!(b[x-y+nrows], M[x, y])
        end
    end

    return Dict("lines_horizontal" => h, "lines_vertical" => v, "diagonals_forward" => f, "diagonals_backward" => b)

end

M = [1 2 3; 4 5 6; 7 8 9]

get_lines(M)

输出:

Dict{String, Vector{Vector{Int64}}} with 4 entries:
  "diagonals_backward" => [[3], [2, 6], [1, 5, 9], [4, 8], [7]]
  "diagonals_forward"  => [[1], [4, 2], [7, 5, 3], [8, 6], [9]]
  "lines_horizontal"   => [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  "lines_vertical"     => [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
python python-3.x matrix julia diagonal
1个回答
0
投票

这是您的 python 问题的解决方案。

from collections import defaultdict

def get_lines(matrix):
    nrows = len(matrix)
    ncols = len(matrix[0])
    
    # Initialize containers for lines
    h = [[] for _ in range(nrows)]  # horizontal lines
    v = [[] for _ in range(ncols)]  # vertical lines
    f = defaultdict(list)  # forward diagonals (i + j constant)
    b = defaultdict(list)  # backward diagonals (i - j constant)
    
    # Iterate through the matrix
    for i in range(nrows):
        for j in range(ncols):
            h[i].append(matrix[i][j])  # horizontal line
            v[j].append(matrix[i][j])  # vertical line
            f[i + j].append(matrix[i][j])  # forward diagonal
            b[i - j].append(matrix[i][j])  # backward diagonal

    # Convert defaultdicts to lists of lists
    forward_diagonals = [f[k] for k in sorted(f)]
    backward_diagonals = [b[k] for k in sorted(b)]

    return {
        "lines_horizontal": h,
        "lines_vertical": v,
        "diagonals_forward": forward_diagonals,
        "diagonals_backward": backward_diagonals
    }

# Example usage
M = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
]

result = get_lines(M)
for key, value in result.items():
    print(f"{key}: {value}")

输出示例:

lines_horizontal: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
lines_vertical: [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
diagonals_forward: [[1], [2, 5], [3, 6, 9], [4, 7, 10], [8, 11], [12]]
diagonals_backward: [[4], [3, 8], [2, 7, 12], [1, 6, 11], [5, 10], [9]]
© www.soinside.com 2019 - 2024. All rights reserved.