-1

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
#################
  • `sorted(set(raw_list))` should work and remove duplicates. – luk2302 Aug 01 '22 at 07:20
  • Does this answer your question? [Removing duplicates in lists](https://stackoverflow.com/questions/7961363/removing-duplicates-in-lists) – luk2302 Aug 01 '22 at 07:21
  • @luk2302 it has some pattern, which i need to keep it in mind. –  Aug 01 '22 at 07:22
  • @luk2302 the upcoming element can be duplicate, will it satisfy this condition –  Aug 01 '22 at 07:23
  • Then you a) would need to provide more examples and state clearly where your code fails for what reason, b) look at the linked post which talks about retaining order, and c) maybe do not sort the list in the first place!? – luk2302 Aug 01 '22 at 07:23
  • What do you mean, "some pattern"? – Amadan Aug 01 '22 at 07:23

2 Answers2

0

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:]))
Amadan
  • 191,408
  • 23
  • 240
  • 301
0

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()