0

My code should recieve a list of numbers and then output on the screen the only numbers which repeat more then once. I don't know why but it don't work with the numbers in the middle of list. My code:

a = [int(i) for i in (input().split())]
a.sort()
for number in a:
    if a.count(number)==1:
        a.remove(number)
    else:
        a.remove(a.count(number)-a.count(number)+number)
for number in a:
    print(number, end=' ')

I tried changing if on while on 4th string, but then the last number is left in the list. It should work like:

Sample Input 1: 4 8 0 3 4 2 0 3 Sample Output 1: 0 3 4

Sample Input 2: 10 Sample Output 2:

Sample Input 3: 1 1 2 2 3 3 Sample Output 3: 1 2 3

Sample Input 4: 1 1 1 1 1 2 2 2 Sample Output 4: 1 2

pookeeshtron
  • 135
  • 1
  • 1
  • 8
  • 3
    `a.count(number)-a.count(number)+number` = `number`, right? You should use `collections.Counter` for this task. – qvpham Jul 05 '16 at 08:28

2 Answers2

1

You could approach this problem using set instead:

a = list(map(int, input().split()))
print(" ".join(map(str, set(i for i in a if a.count(i) > 1))))

Explanation:

Firstly, it looks like you should read up on the map function. Instead of a = [int(i) for i in (input().split())], you can just use list(map(int, input().split())), which is much more Pythonic.

Secondly, the important part of the second line is set(i for i in a if a.count(i) > 1), which just creates a new list containing only the duplicates from a (i.e. [1, 2, 3, 2, 3] becomes [2, 3, 2, 3] and then applies set to it, which converts [2, 3, 2, 3] into {2, 3} (which is a set object).

In case you're wondering what map(str, ...) is for, it's so that you can print each of the elements inside your new set (e.g. {2, 3}).

Community
  • 1
  • 1
sidney
  • 757
  • 1
  • 6
  • 10
1

You can use built-in lib collections to count list items and filter it by a required condition.

import collections

ints = map(int, input().split())
count = collections.Counter(ints)
print filter(lambda x: count[x] > 1, count)
I159
  • 29,741
  • 31
  • 97
  • 132