Home > Mobile >  How to generate sequential subsets of integers?
How to generate sequential subsets of integers?

Time:01-27

I have the following start and end values:

start = 0
end = 54

I need to generate subsets of 4 sequential integers starting from start until end with a space of 20 between each subset. The result should be this one:

0, 1, 2, 3, 24, 25, 26, 27, 48, 49, 50, 51 

In this example, we obtained 3 subsets:

0, 1, 2, 3
24, 25, 26, 27
48, 49, 50, 51 

How can I do it using numpy or pandas?

If I do r = [i for i in range(0,54,4)], I get [0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52].

CodePudding user response:

This should get you what you want:

j = 20
k = 4
result = [split for i in range(0,55, j k) for split in range(i, k i)]
print (result)

Output:

[0, 1, 2, 3, 24, 25, 26, 27, 48, 49, 50, 51]

CodePudding user response:

Maybe something like this:

r = [j for i in range(0, 54, 24) for j in range(i, i   4)]
print(r)
[0, 1, 2, 3, 24, 25, 26, 27, 48, 49, 50, 51]

CodePudding user response:

you can use numpy.arange which returns an ndarray object containing evenly spaced values within a given range

import numpy as np

r = np.arange(0, 54, 4)

print(r)

Result

[0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52]

CodePudding user response:

Numpy approach

You can use np.arange to generate number with a step value of 20 4, where 20 is for space between each interval and 4 for each sequential sub array.

start = 0
end   = 54
out   = np.arange(0, 54, 24) # array([ 0, 24, 48]) These are the starting points
                             # for each subarray

step = np.tile(np.arange(4), (len(out), 1))
# [[0 1 2 3]
#  [0 1 2 3]
#  [0 1 2 3]]


res  = out[:, None]   step

# array([[ 0,  1,  2,  3],
#        [24, 25, 26, 27],
#        [48, 49, 50, 51]])

CodePudding user response:

This can be done with plane python:

rangeStart = 0
rangeStop = 54
setLen = 4
step = 20
stepTot = step   setLen
a = list( list(i s for s in range(setLen)) for i in range(rangeStart,rangeStop,stepTot))

In this case you will get the subsets as sublists in the array.

CodePudding user response:

I dont think you need to use numpy or pandas to do what you want. I achieved it with a simple while loop

num = 0
end = 54
sequence = []

while num <= end:
    sequence.append(num)
    num  = 1
    if num%4 == 0: //If four numbers have been added
        num  = 20
//output: [0, 1, 2, 3, 24, 25, 26, 27, 48, 49, 50, 51]
  •  Tags:  
  • Related