0

I want to write a function that returns the number of duplicate items in an array.

For example:

arr = [2,4,6,3,2,2,4,6]
# this should return 3 since (2,4,6) are repeated in the list
Moe
  • 95
  • 1
  • 2
  • 5

2 Answers2

1

Something like this should work:

def duplicate_in_array(array):
array_len = len(array)
duplicate_set = set()

for i in range(array_len):
    for y in range(i + 1,array_len):
        if array[i] == array[y]:
            duplicate_set.add(array[i])

return len(duplicate_set)

With a double for-loop, you add every duplicate to a set. Since a set can only have the same element once, if your array has three or more times the same element, it will only be added to the set once. Then, you return the set's length.

1

A fairly lazy (my favourite) but quick solution could be to use Counter

This will create a dictionary where:

  • keys are the elements in arr
  • values are the number of occurrences of each element

Steps:

  • Build a Counter with your arr object
  • Build a list of all elements that have a count > 1
  • Get the length of that list
from collections import Counter

c = Counter(arr)
duplicates = len([key for key in c if c[key] > 1])
print("Number of duplicated elements: ", duplicates)

>>> 3

The c object looks like this:

Counter({2: 3, 4: 2, 6: 2, 3: 1})
Xhattam
  • 195
  • 1
  • 11