'Replacing elements and inserting them in next row

def Demand(n):
    x1 = ([[6., 7., 8., 9., 10.],
           [0., 0., 0., 0., 0.],
           [0., 0., 0., 0., 0.],
           [0., 0., 0., 0., 0.],
           [0., 0., 0., 0., 0.]])

    # get index of n in x1[0].
    idx = x1[0].index(n)
    # values to relocate.
    to_add_again = x1[0][idx + 1:]
    # shift x1[0] right (filling left with zeros)
    x1[0] = [0.] * (len(x1[0]) - (idx + 1)) + x1[0][:idx + 1]
    # if we already moved one of elements of to_relocate to a location
    # we do not want to remove it from that location.
    do_not_relocate = set()
    for i in to_add_again:
        while True:
            # draw indices of random element in matrix other than the first row
            ij = (randrange(1, len(x1)), randrange(0, len(x1[0])))
            if ij not in do_not_relocate:
                break
        do_not_relocate.add(ij)
        x1[ij[0]][ij[1]] = i

    print(x1)

    x2 = [7.0, 0, 0, 0, 0]
    for i in x2:
        if i == n:
            x2[0] = 0
    print(x2)
Demand(8)

output: [[0.0, 0.0, 6.0, 7.0, 8.0], [0.0, 0.0, 0.0, 10.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 9.0, 0.0, 0.0]]

[7.0, 0, 0, 0, 0]

Instead of randomly placing the elements in the rows, can I insert the elements to be replaced in the exact next row from the left (that is from index 0)

and the next replace should also continue inserting the elements from where is was left earlier without a 0 in between.

example: if demand(8)

output should be:

[[0.0, 0.0, 6.0, 7.0, 8.0], 
[9.0, 10.0, 0.0, 0.0, 0.0], 
[0.0, 0.0, 0.0, 0.0, 0.0], 
[0.0, 0.0, 0.0, 0.0, 0.0], 
[0.0, 0.0, 0.0, 0.0, 0.0]]

and if next demand(7)

output should be:

[[0.0, 0.0, 0.0, 6.0, 7.0], 
[9.0, 10.0, 8.0, 0.0, 0.0], 
[0.0, 0.0, 0.0, 0.0, 0.0], 
[0.0, 0.0, 0.0, 0.0, 0.0], 
[0.0, 0.0, 0.0, 0.0, 0.0]]

Please help!!!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source