Home > database >  Python list see if contains consecutive numbers but avoid the adjacent/next duplicate
Python list see if contains consecutive numbers but avoid the adjacent/next duplicate

Time:08-01

I want to test if a list contains consecutive integers. But if the next element is duplicate it show avoid it.

For e.g.

raw_list_1 = [400, 401, 402] # this is valid
raw_list_2 = [400, 401, 403] # this is in-valid
raw_list_3 = [400, 401, 401, 401, 402, 403] # this is valid

in the case of raw_list_3 we got the pattern where number can repeat in sequential manner.

my code

raw_list_1 = [400, 401, 402] # this is valid
raw_list_2 = [400, 401, 403] # this is in-valid
raw_list_3 = [400, 401, 401, 401, 402, 403] # this is valid
is_valid_list = sorted(raw_list_3) == list(range(min(raw_list_3), max(raw_list_3) 1))
print(is_valid_list)
False
#################

CodePudding user response:

An optimisation of your method would be to just check that the difference between the first element and the last element, rather than actually generate the list:

sorted_uniques = sorted(set(raw_list))
is_valid_list = sorted_uniques[-1] - sorted_uniques[0] == len(sorted_uniques) - 1

If the sorting trick is not to be used, you can check the difference between consecutive elements:

is_valid_list = all(0 <= y - x <= 1 for x, y in zip(raw_list, raw_list[1:]))

CodePudding user response:

If the first derivative is always in {0, 1} the list is valid.

import numpy as np

def is_valid(arr_like):
    return np.isin(np.diff(arr_like), [0,1]).all()

is_valid(raw_list_1), is_valid(raw_list_2), is_valid(raw_list_3)

#OUTPUT:
#(True, False, True)

If you are sure that all your lists are monotonic not decreasing you could optimize the function in the following way:

def is_valid(arr_like):
    return (np.diff(arr_like)<=1).all()
  • Related