Home > Back-end >  find duplicates in a sorted list by comparing i with i 1
find duplicates in a sorted list by comparing i with i 1

Time:03-08

I have a list sorted in ascending order. I want to find the duplicates in the list by comparing elemnt i with element i 1. I have tried other methods that worked.For example the double loop, but I want to use this method since I am learning python and want to understand why my code is not working. This is my code:

array=[1,1,2,3,3,4,5,6]
def find_duplicates(arr):
  duplicates=[]
  sorted=  sort(arr) #helper function that succesfully sorts a list
  
  for i in range(1, len(sorted)):
      #before=sorted[i-1]
      if i==sorted[i-1]:
          duplicates.append(i) #tried also duplicates.append(sorted[i-1])

  return duplicates #expected: [1,3] 


print(find_duplicates(array)) #actual outcome [1]

I am only getting the firts duplicate in appended to my array. your suggestions will be highly appreciated. Thank you.

CodePudding user response:

You are comparing i with sorted[i-1] instead of comparing the list element which would be sorted[i].

Also, sorted is a keyword in python as there is a function with that name - sorted() so it would be better to use another variable.

CodePudding user response:

There are a couple of opportunities to fix. First, let's not use sorted as a variable name :-) Next, let's clear up a muddling of an index into arr and the value of arr at that index.

def find_duplicates(arr):
    ## ---------------------
    ## feel free to call some other sorting function, but let's not set the return
    ## value to a variable called "sorted" as it clobers this built-in function
    ## ---------------------
    arr = sorted(arr)
    ## ---------------------

    duplicates=[]
    for i in range(1, len(arr)):
        ## ---------------------
        ## Not stricktly needed, but let's define some variables for clarity
        ## ---------------------
        current_value = arr[i]
        prior_value = arr[i - 1]
        ## ---------------------

        if current_value == prior_value:
            duplicates.append(prior_value)

    return duplicates

array=[1,1,2,3,3,4,5,6]
print(find_duplicates(array))

This should give us:

[1, 3]
  • Related