5
$\begingroup$

Suppose I have the following list:

l = {"A", "A", "A", "E", "D", "D", "D", "C", "B", "E", "E", "E", "D", 
  "B", "A", "D", "B", "E", "C", "A", "D", "A", "A", "A", "A", "C", 
  "C", "C", "D", "D", "E"}

I want to count how many two letters I have namely how many AA, AB,... I have in list l. I know this is equivalent of counting the tuples on list l, the tuples are,

Tuples[l // DeleteDuplicates // Sort, 2]

but I am not sure how to count these on l. As an example, there are 5 counts of AA on l. I wonder what is the solution for this?

$\endgroup$
10
$\begingroup$

How about

Partition[l, 2, 1] // Counts

(*
<|{"A", "A"} -> 5, {"A", "E"} -> 1, {"E", "D"} -> 2, {"D", "D"} -> 
  3, {"D", "C"} -> 1, {"C", "B"} -> 1, {"B", "E"} -> 2, {"E", "E"} -> 
  2, {"D", "B"} -> 2, {"B", "A"} -> 1, {"A", "D"} -> 2, {"E", "C"} -> 
  1, {"C", "A"} -> 1, {"D", "A"} -> 1, {"A", "C"} -> 1, {"C", "C"} -> 
  2, {"C", "D"} -> 1, {"D", "E"} -> 1|>
*)
$\endgroup$
7
$\begingroup$

You can also use SequenceCases + Counts:

Counts[SequenceCases[l, {_, _}, Overlaps -> True]]

<|{"A", "A"} -> 5, {"A", "E"} -> 1, {"E", "D"} -> 2, {"D", "D"} -> 3, {"D", "C"} -> 1, {"C", "B"} -> 1, {"B", "E"} -> 2, {"E", "E"} -> 2, {"D", "B"} -> 2, {"B", "A"} -> 1, {"A", "D"} -> 2, {"E", "C"} -> 1, {"C", "A"} -> 1, {"D", "A"} -> 1, {"A", "C"} -> 1, {"C", "C"} -> 2, {"C", "D"} -> 1, {"D", "E"} -> 1|>

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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