Search code examples
pythonmatrixdiagonal

to print all the diagonal elements for a given array


a = [['a','b','c'],
    ['d','e','f','g'],
    ['h','i','j','k'],
    ['l','m','n']]

I need to print the diagonal elements of the given array such as output would be:

[['l'],['h','m'],['d','i','n'],['a','e','j'],['b','f','k'],['c','g']]

Solution

  • I guess it's more or less like this:

        a = [
        ['a','b','c'],
        ['d','e','f','g'],
        ['h','i','j','k'],
        ['l','m','n']
        ]
    
    d = 0
    while True:
      array = []
      j = (len(a)-1)-d
      k = 0
      if j<0:
        k= -j
        j = 0
      while j<len(a) and k<len(a[j]):
        array.append(a[j][k])    
        j+=1
        k+=1
      if len(array) == 0:
        break
    
      print(array)
      d+=1