Reputation:
I searched around and found how to return how many pairs of same value in list. As an example: x = [10,10,20,30,20] => It should return 2 because we have 2 pairs of same value each: (10,10) and (20,20). What is confusing me and do not understand, why the function below is returning result + 1? which leads to wrong output. Output should be 2 but I have 3!! Thank you very much.
x = [20, 30, 20, 30, 20, 40, 30]
freq = {}
count = 0
for item in x:
if (item in freq):
freq[item] += 1
else:
freq[item] = 1
for key, value in freq.items():
count+=value/2
print("Pairs : ",int(count))
Upvotes: 0
Views: 1919
Reputation: 887
The below line of code is not what you are looking for :
set(ar).intersection(mylist)
It just prints out the number of unique elements in your list.
You could do something like this :
freq = {}
count = 0
for item in x:
if (item in freq):
freq[item] += 1
else:
freq[item] = 1
for key, value in freq.items():
count+=value/2
print("Pairs : ",count)
Upvotes: 1