I would like to set up a function which has to return True if at least two arguments of a given List are equal.
So if I give {1,4,6,2}
to the function it has to return False
(since none of his arguments are equal) and the same would happen if I gave {{1,2,3},{2,3,4}}
, while if I gave {1,2,3,1,4}
or {{1,2,3},{2,0,0},{1,2,3},{2,1,2}}
it has to return True
.
I know this is a very simple problem and i think you can easily tell me a convenient way to achieve that.
Answer
If there are repeated elements in the list, then calling Union[]
on it will shorten it so that this element only appears once, so a simple implementation would be to test these lengths:
test[list_] := Length[Union[list]] != Length[list]
If you wanted to know which elements where repeated, you this could be accomplished by using Gather[]
to collect identical elements, and picking out which groups have more then one element.
repeats[list_] := Select[Gather[list], Length[#] > 1 &][[1 ;;, 1]]
Note, I'm using Union rather then DeleteDuplicates[]
since (as Mr. Wizard corrected me) it is faster. I can't say why except that DeleteDuplicates[]
retains the order of elements which may require slightly more bookkeeping. And in this case we don't care about the book keeping. Naturally if you really needed something really speedy, a better solution exists which doesn't search through the entire list, but stops if just a single duplicate is found, Mr. Wizards Answer is just such an function, since Signature
exits early if duplicates exist, though it becomes slower if no duplicates are present, it's a trade off.
Comments
Post a Comment