I have the following index that I need to programme so for different svalues of inputs has this form

Viewed 44

Does anybody know how could I make this type of index on Python?

enter image description here

1 Answers

If I understand you correctly, you want to get a matrix with values of a given sequence, shifted one item left each row. Sort of:

seq = [1,2,3,4,5]
arr = [[0]*len(seq) for _ in seq]
for i in range(len(seq)):
    arr[i][:len(seq)-i] = seq[i:]

which results in an array

[[1, 2, 3, 4, 5],
 [2, 3, 4, 5, 0],
 [3, 4, 5, 0, 0],
 [4, 5, 0, 0, 0],
 [5, 0, 0, 0, 0]]

If the matrix is used for calculations only and remains unchanged, then I would use as_strided from numpy.lib.stride_tricks:

import numpy as np
from numpy.lib.stride_tricks import as_strided

seq = [1,2,3,4,5]
arr = np.r_[seq, np.zeros(len(seq)-1)]

itemsize = arr.dtype.itemsize
count = len(seq)

arr = as_strided(arr, shape=(count, count), strides=(itemsize, itemsize))

arr will only be twice as large as seq, while the view is:

array([[1., 2., 3., 4., 5.],
       [2., 3., 4., 5., 0.],
       [3., 4., 5., 0., 0.],
       [4., 5., 0., 0., 0.],
       [5., 0., 0., 0., 0.]])
Related