Home > Software design >  How do I create an array as explained below?
How do I create an array as explained below?

Time:11-08

if I have to create a NumPy array with the variable inputs (2,3,2), the output is 0,1,4,5,8,9

This is because 1 is the number of entries in each block, 3 is the number of blocks and 2 is the number of entries spliced per block.

What would I need to include in my code?

CodePudding user response:

I think a simple nested for loop to iteratively build the array will do here:

import numpy as np

def makeArr(x, y, z):
    arr = np.array([])
    cur = 0
    for i in range(y):
        for j in range(x):
            arr = np.append(arr, [cur])
            cur  = 1
        cur  = z # Skip z numbers
    return arr
    
print(makeArr(4, 3, 2))

CodePudding user response:

Something like this should work according to your description.

import numpy as np

def get_my_np_array(num_entries, num_blocks, num_spliced):
    result = np.array([])
    start = 0
    end = num_entries

    for _ in range(num_blocks):
        result = np.concatenate((result, np.arange(start, end)), axis=None)
        start = end   num_spliced
        end = start   num_entries

    return result

print(get_my_np_array(4, 3, 2)) 
# Output: [ 0.  1.  2.  3.  6.  7.  8.  9. 12. 13. 14. 15.]

Basically, you iterate over the number of blocks you need. For each block you define a start point and end point. Then use np.arange(start, end) to generate a numpy array and combine it with the overall result and return result in the end.

  • Related