1

I have a matrix like the following:

matrix = [
    ["a", "b", "c", "d"],
    ["e", "f", "g", "h"],
    ["i", "j", "k", "l"],
    ["m", "n", "o", "p"]
]

And i'm trying to find the diagonals, but when I say diagonals I mean that I want all of the letters that are "diagonal" to eachother. Example, the ideal output would be:

["a", "eb", "ifc", "mjgd", "nkh", "ol","p"]

(I consider that a unique letter is diagonal to itself, and in this example it shows that I start from "a" which is the matrix[0][0] element, then from the second row to the second element etc...)

I have few ideas on how to approach this problem but I thought something like this

for row in matrix:
  for i in range(len(row)):
    for j in range(i, len(row)):
      my_list.append(matrix[?][?])

I know it's not a lot but I can't manage how to declare the pattern that I want as index of list Thank you for your help.

Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
MM1
  • 912
  • 1
  • 10
  • 28
  • Take a smaller 2x2 matrix and literally write out the indices of the elements of diagonals. Do the same with a 3x3 matrix and a 4x4 one. Write out all the indices _on a piece of paper_ and look for the pattern. Then write 3 functions that extract diagonals from 2x2, 3x3 and 4x4 matrices. Search for patterns in your code. Look for constant numbers: can you use variables instead? What would these variables mean? Where would their values come? – ForceBru Nov 28 '19 at 19:29
  • Already done that but thanks – MM1 Nov 28 '19 at 19:31
  • 1
    [Here's](https://gist.github.com/goedel-gang/32220c2b6771964d408cbfeef72fd8e6) an implementation specifically to list trailing diagonals in (somewhat terse) pure Python. You can try and translate it into a full set of loops if you like. – Izaak van Dongen Nov 28 '19 at 19:44

0 Answers0