python to find the duplicates in a range in list code example
Example 1: count the duplicates in a list in python
some_list=['a','b','c','b','d','m','n','n']
my_list=sorted(some_list)
duplicates=[]
for i in my_list:
if my_list.count(i)>1:
if i not in duplicates:
duplicates.append(i)
print(duplicates)
Example 2: Function to find a duplicate element in a limited range list
def findDuplicate(A):
xor = 0
# take xor of all list elements
for i in range(len(A)):
xor ^= A[i]
# take xor of numbers from 1 to `n-1`
for i in range(1, len(A)):
xor ^= i
# same elements will cancel each other as a ^ a = 0,
# 0 ^ 0 = 0 and a ^ 0 = a
# `xor` will contain the missing number
return xor