You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

矩阵右上对角线单词迭代需求:含主对角线及子串输出

Hey there! Let's work through your two problems one by one. First, let's break down why you're hitting index errors when trying to include the main diagonal, then we'll adjust the code to generate all those required substrings for each diagonal.

Understanding the Original Code

Your original code loops over i from 0 to len(matrix)-2, which only covers diagonals where the sum of row and column indices (row + col) is less than len(matrix)-1. When you try to extend this to include the main diagonal (and beyond), you run into index out-of-bounds because your matrix has more rows (6) than columns (5) — some combinations of j and i-j end up referencing a column that doesn't exist.

Step 1: Fix the Index Out-of-Bounds Issue

To safely include all valid diagonals (including the main one), we need to account for both the number of rows and columns. Each diagonal can be identified by the sum k = row + col, which ranges from 0 to (rows-1)+(cols-1) (since the maximum row is 5, max column is 4, so max k is 9).

For each k, we calculate the valid range of row indices j to ensure the corresponding column index c = k-j stays within bounds:

  • The largest possible row index for k is min(rows-1, k) (can't exceed the last row)
  • The smallest possible row index is max(0, k - (cols-1)) (ensures c = k-j doesn't exceed the last column)

Step 2: Generate All Required Substrings

For each diagonal, first collect its characters in the same order as your original code (from lower rows to upper rows). Then, generate every possible consecutive substring starting from each character and extending to the end of the diagonal sequence. For example, if a diagonal is ["n", "g", "p"], we need 'n', 'ng', 'ngp', 'g', 'gp', 'p'.

Full Working Code

matrix = [ ["a", "p", "p", "l", "e"], ["a", "g", "o", "d", "o"], ["n", "n", "e", "r", "t"], ["g", "a", "T", "A", "C"], ["m", "i", "c", "s", "r"], ["P", "o", "P", "o", "P"]]
rows = len(matrix)
cols = len(matrix[0]) if rows > 0 else 0

# Iterate over all valid diagonal sums (row + column)
for k in range(rows + cols - 1):
    # Collect characters for this diagonal (matches original code's order)
    diagonal_chars = []
    start_j = min(rows - 1, k)
    end_j = max(0, k - (cols - 1))
    # Traverse rows from bottom to top for this diagonal
    for j in range(start_j, end_j - 1, -1):
        col = k - j
        diagonal_chars.append(matrix[j][col])
    
    # Generate all consecutive substrings
    for start_idx in range(len(diagonal_chars)):
        for end_idx in range(start_idx + 1, len(diagonal_chars) + 1):
            substring = ''.join(diagonal_chars[start_idx:end_idx])
            print(substring, end=' ')
    print()  # Optional: add a new line after each diagonal's substrings

What This Code Does

  1. Avoids Index Errors: By calculating valid row ranges for each diagonal sum k, we never reference a column index outside the matrix's bounds.
  2. Includes All Diagonals: Covers every possible top-right direction diagonal, including the main diagonal.
  3. Generates All Substrings: For each diagonal's character sequence, it creates every possible substring starting at each position and extending to any subsequent position — exactly the output you described.

Testing this code will give you output segments like:

a 
a ap p 
n ng ngp g gp p 
g gn gno gnol n no nol o ol l 

内容的提问来源于stack exchange,提问作者MM1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:57:46