Search code examples
pythonarraysmatrixsequential

Python: Matrix w/ Sequential Values


I need to do the following:

  1. Create a variable result as an array of length m.
  2. For each row i from 0 to m-1:

    a. Set result[i] to a new array of length n.

    b. For each column j in row i, set that element to (i*n)+j.

  3. When you’ve computed all the elements, return result.

So far, I have the following:

     def f2(m, n):
         result = [""] * m
         for i in range(0, m):
             result[i] = [""] * n   
         for i in result:
             for j in i:
                 result.append(i*n+j)
         return result

This, however, just results in an error.

Any help/suggestions? Thank you


Solution

  • Here you go:

    def f2(m, n):
        #First, let's create a list with the size of m, and
        #each row with the size of n.
        result = [[0 for _ in range(n)] for _ in range(m)]
        #now, you can loop through it easily.
        for i in range(m): #outer list
             for j in range(n): #inner list
                 result[i][j] = i*n+j #put it there :)
        return result
    

    Hope this helsp!