I have a list of positive and negative ones {1,1,-1,1,1,-1,1,-1,1,-1,-1,1,1,1,-1} And I want to find and highlight the subsequence of the lists that have the pattern {...,1,1,___,-1,-1,...}. So ideally my output would be {1,1,-1,1,1,-1,1,-1,1,-1,-1,1,1,1,-1}.
1
-
$\begingroup$ related: 95912 $\endgroup$ – Kuba♦ Jan 28 '17 at 22:02
Add a comment
|
$\begingroup$
$\endgroup$
2
list = {1, 1, -1, 1, 1, -1, 1, -1, 1, -1, -1, 1, 1, 1, -1};
SequenceCases[list, {a___, Shortest[b : PatternSequence[1, 1, ___, -1, -1]], c__} :>
Flatten[{a, Style[#, Bold, Red] & /@ {b}, c}]][[1]]
Note: the subsequence starting with the first entry also satisfies your pattern, and it can be obtained by removingShortest
above or by changing it to Longest
:
SequenceCases[list, {a___, b : PatternSequence[1, 1, ___, -1, -1], c__} :>
Flatten[{a, Style[#, Bold, Red] & /@ {b}, c}]][[1]]
-
$\begingroup$ Is there a way to find the first time that pattern occurs? The code is taking a really long time to run with your solution, and I think finding the first occurrence might still give me what I need. $\endgroup$ – xanadu Jan 28 '17 at 23:23
-
1$\begingroup$ @xanadu, using the third argument
SequenceCases[list, {a___, b : PatternSequence[1, 1, ___, -1, -1], c__} :> Flatten[{a, Style[#, Bold, Red] & /@ {b}, c}], n]
gives the firstn
matches. $\endgroup$ – kglr Jan 28 '17 at 23:53