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
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.
A fairly lazy (my favourite) but quick solution could be to use Counter
This will create a dictionary where:
arr
Steps:
arr
objectfrom 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})