Question

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

Was it helpful?

Solution 2

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!

OTHER TIPS

Use list comprehension:

def f2(m, n):
    return [[i*n+j for j in range(n)] for i in range(m)]
for i in result:
    for j in i:

In this nested loop, i iterates over the rows of result and j iterates over the cell contents. Thus, in the loop body:

        result.append(i*n+j)

this line attempts to multiply a row by n, add j (a string) to that, and append the output of that to result. No part of that is what you want to do. You could fix this by iterating over the indices and assigning to elements instead of appending:

for i in range(m):
    for j in range(n):
        result[i][j] = i*n+j

but it's easier to build the whole array the way you want it with range instead of initializing it with garbage and assigning the elements:

def f2(m, n):
    return [range(n*i, n*i+n) for i in xrange(m)]

or if you're on Python 3:

def f2(m, n):
    return [list(range(n*i, n*i+n)) for i in range(m)]

or if list comprehensions are strange and unreadable to you:

def f2(m, n):
    result = []
    for i in range(m):
        result.append(list(range(n*i, n*i+n)))
    return result
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top