Home > front end >  Check the duplicate element in an array using set in python
Check the duplicate element in an array using set in python

Time:07-30

Scan and check the numbers in an array if it is repeated, if true print yes, else print no So what I'm trying to do is convert them into a set (and list)

a = [int(v) for v in input().split()]
b = set(a)

and check if the occurrence of an element in list a is equal to that is set b, but currently, there's no such function to count the occurrence in set b, isn't it? I'm dumb so pls help

for i in range(len(a)):
    if a.count(a[i]) == ..occurrence in set b..:
        print("NO")
    else:
        print("YES")

example input:

1 2 3 2 3 4

output:

NO
NO
NO
YES
YES
NO

CodePudding user response:

Given the problem description you need a code that identifies if an item of a list appears in it more than once. Here's one way you can do it,

from collections import Counter

# Input list with duplicates
numbers = [1, 2, 3, 2, 3, 4]

# Count of each list element
counted_numbers = Counter(numbers)

# Chech occurrence of each list element
for el in numbers:
    if counted_numbers[el] > 1:
        print('YES')
    else:
        print('NO')

The code uses Counter to create a dictionary with number of occurrences of each list element. In other words, counted_numbers are a dictionary where the keys are unique elements of the list numbers and the values are the number of times they appear in the list.

The second part of the code loops through the original list and checks how many times it appears as reported by Counter. If its more than one, it prints YES.

Temporary note: the output is different than in your example, let me know if this is not what you're looking for.

CodePudding user response:

I think this is what you're looking for:

for i in range(len(a)):
    if a[i] in a[:i]:
        print("YES")
    else:
        print("NO")

If the number at index is appeared on the left hand side of the current index, it is printed YES, otherwise NO.

CodePudding user response:

count = set()

for num in nums:

  `if num in count:`

print("YES")

else:

print("NO")

count.add(num)

  • Related