Such a task to find all the additional diagonals (parallel main diagonals) Began to solve so, such a solution gives only one additional diagonal and that's all I need to give the rest.

def checkio(matrix): results=[] x=0 for k,row in enumerate(matrix): for i,elm in enumerate(row): if(x+1==i): results.append(elm) x=i break results.append('---') print(results) if __name__ == '__main__': checkio([[11, 2, 4, 7], [ 4, 5, 6, 0], [10, 8, -12, -1], [10, 8, -12, -1]])#<---[2, '---', 6, '---', -1, '---', '---'] 
  • The nested loop is not needed here: i always as a result of its execution becomes equal to x + 1, x increases by one, elm becomes equal to row [i]. And so you run only on the upper right corner of the matrix, forgetting about the lower left. - ⷶ ⷩ ⷮ ⷪ ⷩ

1 answer 1

If we talk only about square matrices, then we can modify chekio like this:

 def checkio(matrix): results = [] for counter in range(1, len(matrix)): diag_length = len(matrix) - counter results.extend([ [matrix[i][i + counter] for i in range(diag_length)], # top-right [matrix[i + counter][i] for i in range(diag_length)] # bottom-left ]) print(results) 

counter here makes sense the distance from the main diagonal to the parallel diagonal (there are two parallel at a given distance: in the right-top corners (top-right) and left-bottom (bottom-left) from the main diagonal). The distance between adjacent diagonals is understood to be equal to one. We start from the unit so as not to take into account the main diagonal itself.

 # [[2, 6, -1], [4, 8, -12], [4, 0], [10, 8], [7], [10]] 
  • The meaning of dashes ('---'), as I understand it, is cosmetic, so there are no answers in them - ⷶ ⷩ ⷮ ⷪ ию
  • And the results I have a list of the desired diagonals - ⷶ ⷩ ⷮ ⷪ ⷩ
  • By the way, it is possible that the upper limit in range(1, len(matrix)): for counter it is necessary to decrease by one, because the question of whether the diagonal containing a single element is parallel to something is quite reasonable. - ⷶ ⷩ ⷮ ⷪ ⷩ
  • Great) you explained it very carefully) - Constantine