1

How do I return output or an object that looks like any of the following for an array that has sequences of linear values

First sequence [0:9] or Last sequence [502:511] or Both sequences [0:9,502:511]

s = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511])

4
  • 1
    I'm confused about what you're asking here. could you give us some more concrete examples? Commented Aug 19, 2021 at 15:04
  • Add more conditions, because every single and two element slice is linear Commented Aug 19, 2021 at 16:52
  • Do you need them to be linear, or do you need them in Arithmetic progression? Commented Aug 19, 2021 at 16:54
  • Which is the starting point? s or [[0,9],[502,511]]? Commented Aug 19, 2021 at 17:14

1 Answer 1

1

I wrote a quick function that shows you how you can extract these arithmetic sequences from an array. I used range objects to represent them in the end, but you can just as well replace them with slice objects if you prefer. Anyway note that this only works if all sequences have a length of at least two, otherwise it is not possible to uniquely determine what values belong to what sequence. (Any two values trivially form an arithmetic sequence!)

Also note that this works for arbitrary (also negative) step sizes!

import numpy as np

def rangify(s):
    # get start and end point of each arithmetic sequence
    limits_bool = np.concatenate([[True], np.diff(s, 2) != 0, [True]])
    # get limits of the arithmetic sequences
    limits_int = s[limits_bool].reshape(-1, 2)
    # second value in each arithmetic sequence
    second = s[np.nonzero(limits_bool)[0][0::2] + 1]
    # compute step size by subtracting first
    step = second - limits_int[:, 0]
    # use range objects to represent these arithmetic sequences
    return [range(start, stop+step, step) for (start, stop), step in zip(limits_int, step)]



s = np.array([0, 1, 2, 3, 4, 5, 6, 502, 503, 504, 505, 506, 507, 508, 26, 24, 22, 20])
print(rangify(s))
print(np.concatenate([list(x) for x in rangify(s)]))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.