Home > OS >  Is there a way to check if a list contains unique values that only occur once in a list contiguously
Is there a way to check if a list contains unique values that only occur once in a list contiguously

Time:10-21

I am trying to find a way to check if a list contains contiguous elements which are not duplicated.

For example,

  • A = [1, 1, 4, 2, 2, 2] this list contains contiguous elements which are not duplicated.
  • A = [1, 1, 4, 4, 3, 4, 7, 7, 7] this list does not contains contiguous elements which are not duplicated. Here the value 4 is contiguous from index 2 and 3 but its occurs again at index 5 which is not acceptable.

Basically a unique value should only occur once in a list contiguously.

Is there any means where the time complexity should be less than O(n^2).
Also, is there some method in itertools through which I could acheive this?

CodePudding user response:

Here are some examples which may help:

# Sorting based Python implementation
# to check whether the array
# contains a set of contiguous integers
 
def areElementsContiguous(arr, n):
    # Sort the array
    arr.sort()
     
    # After sorting, check if
    # current element is either
    # same as previous or is
    # one more.
    for i in range(1,n):
        if (arr[i] - arr[i-1] > 1) :
            return 0
    return 1
 
# Driver code
arr = [ 5, 2, 3, 6, 4, 4, 6, 6 ]
n = len(arr)
if areElementsContiguous(arr, n): print("Yes")
else: print("No")
 
# This code is contributed by 'Ansu Kumari'.

Code is from https://www.geeksforgeeks.org/check-array-contains-contiguous-integers-duplicates-allowed/ Another reference is: Check if numpy array is contiguous?

CodePudding user response:

You can use one for loop, within the built-in method in.

A = [1, 1, 4, 4, 3, 4, 7, 7, 7]

def is_contiguous_list (lst):
  for i in range(len(lst)-1):
    if lst[i]!=lst[i 1] and lst[i] in lst[i 1:]:
        return (lst[i], " is found duplicated in another place!")
  return ("It's okay")

print (is_contiguous_list(A))

Output:

(4, ' is found duplicated in other place!')

  • Related