I came up with this logic to count the duplicate 1 take input for list length 2 take input of list 3 search in list for the values from zero to last index increment the counter. I am getting error can anyone help to fix it, I know my this not accurate way to do this can someone help me out
n = int(input())
l1=[]
for i in range(n):
l1.append(input())
print(l1)
count1=0
count2=0
count3=0
count4=0
for j in range(n):
if 1 in l1[0,n-1]:
count1 =count1 1
elif 2 in l1(0,n-1):
count2=count2 1
elif 3 in l1(0,n-1):
count3= count3 1
elif 4 in l1(0,n-1):
count4=count4 1
print(count1)
input 4 1 1 2 3 4 output should be 2
CodePudding user response:
Simply use set()
to remove the duplicates from the original list, then take the length of the original list minus the length of the new set:
s = set(l1)
count = len(l1) - len(s)
I don't think this is the optimal way to do it, but it is the shortest and most intuitive way.
CodePudding user response:
There is a pre built function in list to count the elements
data = [1,2,3,4,1,4]
print("Count of 1 =", data.count(1))
print("Count of 2 =", data.count(2))
print("Count of 3 =", data.count(3))
print("Count of 4 =", data.count(4))
But if the number of duplicate elements is what is expected then count of all the elements and sort only those greater than 1.
Get all number of elements which are duplicate
data = [1,2,3,4,1,4]
print(len([data.count(x) for x in list(set(data)) if data.count(x)>1]))