TransWikia.com

Combine list elements preceding a specific element

Mathematica Asked by user55405 on August 12, 2021

Consider the following list:

{"END", "END", "a", "b", "END", "p", "q", "END", "t", "END"}

I want to combine elements that precede the marker element "END"; I also wish to include the marker with the combined elements. Here’s the desired output:

{{"END"}, {"END"}, {"a", "b", "END"}, {"p", "q", "END"}, {"t", "END"}}

I’m looking for an elegant way of performing this using Mathematica’s in built functions, without needing to use procedural programming (though it would be easy to do so).

Here’s a way of doing it that doesn’t quite work, due to it not handling the two consecutive markers at the start. Even if it does work, I’m not sure if it would be very efficient or elegant:

Flatten /@ 
 SequenceCases[
  SplitBy[{"END", "END", "a", "b", "END", "p", "q", "END", "t", 
    "END"}, # === "END" &], {_, {"END"}}]

(* Outputs: {{"a","b","END"},{"p","q","END"},{"t","END"}} *)

One Answer

Split[list, # != "END" &]

{{"END"}, {"END"}, {"a", "b", "END"}, {"p", "q", "END"}, {"t", "END"}}

Also

SequenceReplace[list, {a : Except["END"] ..., "END"} :> {a, "END"}]

{{"END"}, {"END"}, {"a", "b", "END"}, {"p", "q", "END"}, {"t", "END"}}

and

TakeList[#, 
   Differences[
    Union @@ Join[{{0}}, Position[#, "END"], {{ Length@#}}]]] &@list

{{"END"}, {"END"}, {"a", "b", "END"}, {"p", "q", "END"}, {"t", "END"}}

Correct answer by kglr on August 12, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP