0

Write a program that takes as input a list of numbers in one line and displays on the screen in one line the values that occur in it more than once.

Input: 4 8 0 3 4 2 0 3 (after sort: 0 0 2 3 3 4 4 8)

Output: 0 3 4

arr = list(map(int, input().split()))
arr.sort()
arr1 = list(dict.fromkeys(arr))
print(arr1)
kebyzak
  • 21
  • 1
  • 4

2 Answers2

2

You can do it with sets:

>>> s = [0, 0, 2, 3, 3, 4, 4, 8]
>>> {i for i in s if s.count(i) > 1}
{0, 3, 4}

Now, s.count is quite expensive for large lists, so you can store the counts in a dict in O(n) and use that instead:

counts = {}
for i in s:
    counts[i] = counts.get(i, 0) + 1

>>> {i for i in s if counts[i] > 1}
{0, 3, 4}
Jarvis
  • 8,494
  • 3
  • 27
  • 58
  • Really like this, nice one. – S3DEV Jan 10 '21 at 12:54
  • The fact that you use a set here has no extra gain... You're still doing `O(n^2)` because you're looping a list and calling `list.count` on each element... Maybe you meant `[i for i in set(s) if s.count(i) > 1]`. Anyway, `Counter` is the way to go here – Tomerikoo Jan 10 '21 at 12:56
  • I was just updating the answer .. @Tomerikoo – Jarvis Jan 10 '21 at 12:57
0

Exactly for your usecase:

from itertools import groupby


arr = list(map(int, input().split()))
arr.sort()


print([key for key, group in groupby(arr) if len(list(group)) > 1])
Leemosh
  • 883
  • 6
  • 19