Python, 143 bytes
There are already some very good Python answers out there (see @dieters, @ppperry & @xnor answers) so I decided to take a different approach, have some fun with recursion and python lambda
functions and see what could I come up with. This is not even close to the best answers here but it was fun to think.
The program takes the integer list as a parameter of function p
and returns a list containing non-unique elements.
p=lambda i:[j for j in(lambda n:[]if len(n)<=1 else[(lambda x:x[0]if len([1 for o in x[1:]if x[0]==o])==1 else 'N')(n)]+p(n[1:]))(i) if j!='N']
Two line version for better readability:
p=lambda i:[j for j in(lambda n:[]if len(n)<=1 else[(lambda x:x[0]if
len([1 for o in x[1:]if x[0]==o])==1 else 'N')(n)]+p(n[1:]))(i) if j!='N']
Short Explanation
The inner lambda
takes a list x
as a parameter and returns the first element of such list if it is repeated only once in the rest of the list (x[1:]
). If not it returns 'N'
.
The lambda
in between the outer and inner lambdas
is the one in charge of the recursive search. This returns a list containing the non-unique elements and plenty of 'N's
. This is the one which takes the integer list as a parameter.
The outer lambda
filters the resulting list getting rid of the unwanted 'N's
.
Test cases
p([])
[]
p([-1,0,1])
[]
p([3, 0, 0, 1, 1, 0, 5, 3])
[3,0,1]
[-1, 0, 1]
, can we input (replace \n with newlines):"-1\n0\n1"
? \$\endgroup\$