0

I would like to write a short Python function that will detect the duplicate number in a list of integers and print out that number to standard output. The input 5;0,1,2,3,0 is generated by these lines already:

import sys for line in sys.stdin: print line,

And I am wondering whether I could use the following code (part of the above for loop) to get the desired output of "0":

seen = set()
for num in line:
    if num in seen:
        print num
    else:
        seen.add(num)

So far this gives me the output: 5;0,1,2,3,0 , , , 0

I just need to get rid of the comma lines and keep the 0... This is for Python in general, not necessarily Python 3.

Kei J.
  • 1
  • 1
  • 4

3 Answers3

1

You can do that with this short code

In[43]: a = [0,1,2,3,0]
        print [j for j, i in enumerate(a) if j in a[i+1:]]
Output
[0]
Alexis G
  • 1,259
  • 3
  • 14
  • 27
  • Thanks, I think this would work well too...would this syntax work for Python 3? The compiler gives me an error at the "for" expression. – Kei J. Nov 07 '15 at 02:18
0

One little correction: you want to add the number to the set seen if you haven't seen it before:

line = [5,0,1,2,3,0]
seen = set()
for num in line:
    if num in seen:
        print num
    else:
        seen.add(num)

This produces the desired output of a single 0.

Prune
  • 76,765
  • 14
  • 60
  • 81
0

A small refinement to the code from Alexis G which makes the line more generic:

a=[1,6,2,4,6,5]
print [j for i, j in enumerate(a) if j in a[i+1:]]
[6]

a=[1,6,2,4,6,5,2]
print [j for i, j in enumerate(a) if j in a[i+1:]]
[6, 2]

a = ['a','d','c','d','f','b','f']
print [j for i, j in enumerate(a) if j in a[i+1:]]
['d', 'f']
Hack Saw
  • 2,741
  • 1
  • 18
  • 33