Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a list of lists. Modify elements in the list

Requirement:

Define the function createMatDimXDim(dim) This function receives a positive integer number greater or equal than 2 and returns a square matrix of dimension dim x dim, where the contents are numbers which are equal to the row number multiplied by 10 plus the column number.

Expected output:

print (createMatDimXDim (4)) 
[[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]]

My code:

def createMatDimXDim (dim):
    lis=[[0] for i in range(dim)]
    for i in range(dim):
        lis[i][0]=i*10
        for i in range(dim):
           lis[i].append(int(lis[i][0])+1)
    return lis

Ouput of my code:

[[0, 1, 1, 1, 1], [10, 1, 11, 11, 11], [20, 1, 1, 21, 21], [30, 1, 1, 1, 31]]

I wanted to do this:

lis[i].append(int(lis[i][i-1])+1)

But it gives me an IndexError.

like image 330
Rui Yu Avatar asked Dec 05 '25 19:12

Rui Yu


1 Answers

def createMatDimXDim (dim):
    lis=[[0] for i in range(dim)]
    for i in range(dim):
        lis[i][0]=i*10
        for j in range(dim-1):               # for the nested loop you need to use a new 
                                             # variable j
           lis[i].append(int(lis[i][j])+1)
    return lis

createMatDimXDim(4)
# [[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]]

Another option with list comprehension:

dim = 4
[[i * 10 + j for j in range(dim)] for i in range(dim)]
# [[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]]
like image 54
Psidom Avatar answered Dec 08 '25 15:12

Psidom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!