Home > Software design >  Create a matrix in Python with sequences increasing
Create a matrix in Python with sequences increasing

Time:08-28

I am working on a project and I need to be able to create a function that takes in a value (n) and returns a matrix with increasing values.

ex: Given x = 2, return = [[1],[1, 2]]

Given x = 5, return = [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4],[1, 2, 3, 4, 5]]

Below is what I have thus far:

def matrixIncrease(n):
    lst = []
        
    for i in range(n):
        lst.append([])
        for j in range(0, n):
            lst[i].append(j)
    return lst

print(matrixIncrease(3))

This will just return

[[0, 1, 2], [0, 1, 2], [0, 1, 2]]

So it looks like the correct amount of inner list are being created. But, the values inside the list are not increasing correctly. Any suggestions?

CodePudding user response:

Maybe you could try this List Comprehension way:

It's quite self-explnatory in the code, just play/experiment with different i and j to see the effects of changes...

Basically the j is to iterate and increase the numbers in each loop.


def create_sub(n):
    ''' create n sub_lists: each list has increasing items:
        [1], [1, 2], [1, 2, 3], .... [1, ... n] '''
    sub_matrix = [[j  1 for j in range(0, i)]        # j - for col values
                        for i in range(1, n   1)]    # i - control rows
    return sub_matrix

>>>create_sub(5)
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]

>>>create_sub(8)
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7, 8]]

CodePudding user response:

You could try this:

all_ = []
def matrixIncrease(n):
    if n == 1:
        all_.append([1])
        return[1]
    j=[]
    for i in range(1,n 1):
        j.append(i)
    matrixIncrease(n-1)
    all_.append(j)
  

matrixIncrease(7)
print(all_)
  • Related