5
$\begingroup$

I have a list of Data, e.g.,

list1={0, 1, 1, 1, 1, 2, 2, 3, 3}

list2={0, 1, 1, 1, 1, 2, 2, 3, 3, 0}

and I want to get as an output True or False if I have only even number of Data of similar or not. in the above example I like to write a code that returns False for list1 and True for list2, since in list1 I have only one 0, but in the list2 there are even number of each number.

Thanks!

$\endgroup$
0

4 Answers 4

9
$\begingroup$

Using Counts

f = And @@ EvenQ[Values[Counts[#]]] &
{f[list1], f[list2]}

{False, True}

$\endgroup$
3
  • 5
    $\begingroup$ +1. Or f = Counts /* AllTrue[EvenQ] $\endgroup$
    – WReach
    Nov 1, 2017 at 14:27
  • 1
    $\begingroup$ Yours is much concise. I think you should post it as a separate answer. $\endgroup$ Nov 1, 2017 at 14:30
  • $\begingroup$ I did, but when I saw yours, I deleted it :) I shall undelete. $\endgroup$
    – WReach
    Nov 1, 2017 at 14:36
11
$\begingroup$

Given:

f = Counts /* AllTrue[EvenQ];

Then:

f[list1]
(* False *)

f[list2]
(* True *)
$\endgroup$
6
$\begingroup$

You can use the Tally function:

Tally[list]
tallies the elements in list, listing all distinct elements together with their multiplicities.

So as

And@@EvenQ[Tally[list1][[;; , 2]]]

or

And@@EvenQ[Tally[list2][[;; , 2]]]
$\endgroup$
3
$\begingroup$
check[list_] := If[
  Cases[EvenQ[Count[list, #] & /@ Union[list]], False] == {},
  True, False]

check[list2]

True

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.