Tag Info

New answers tagged

1

I have found some other ways (than Block[...]) to "force" the matching, but with some slight modifications of the code. 1. Whatever the choice you make here : {f1, f2} = {Hold, Hold}; or {f1, f2} = {HoldComplete, HoldComplete}; or {f1, f2} = {Unevaluated, HoldPattern}; the two following approaches work (and give the same results) : -> Using /; : ...


5

The rules seem to be amenable to a recursive regular expression: extract[s_] := StringCases[s, RegularExpression["b|c|(a(?R)*d)"]] extract["abdcbaacdabbdd"] (* {"abd", "c", "b", "aacdabbdd"} *) Further examples: extract["b"] (* {"b"} *) extract["bcbbc"] (* {"b", "c", "b", "b", "c"} *) extract["ad"] ...


3

rules = {a -> 1, b -> 2, c -> 3}; FilterRules[rules, b] (* {b -> 2} )* or Cases[{a -> 1, b -> 2, c -> 3}, PatternSequence[b -> _]] (* {b -> 2} )*


4

I was able to match your example, but I'm not sure I completely grasped the problem! exampleStr = "abdcbaacdabbdd" checkSubStr[str_String] := And @@ ((Count[Take[Characters@str, #], "a"] >= Count[Take[Characters@str, #], "d"]) & /@ Range[StringLength@str]) StringCases[exampleStr, Shortest@ tot : ("b" | "c" | (x : ("a" ~~ ___ ~~ "d")) /; ...


2

Not anyhere elegant as the OP's own method, but ... staying in the String universe may be a good alternative. Stealing @Aisamu's string pattern and using only String functions: ClearAll[cssF, strngCF]; cssF = Function[{s}, And @@ Flatten[{Equal @@ (StringCount[s, #] & /@ {"a", "d"}), (StringCount[#, "a"] >= StringCount[#, "d"] ...


1

Would that be ok? NotebookDelete /@ Select[ Cells[EvaluationNotebook[], GeneratedCell -> False ], StringCount[ StringJoin @@ Flatten[List @ First[NotebookRead[#]] /. RowBox | BoxData -> List], Except[{" ", "\n", "\[IndentingNewLine]"}]] == 0 & ]


1

Thank you for a well-written question with complete code that made this reasonable to answer. Welcome to Mathematica Stack Exchange. :-) You do not need UpValues definitions here. That would only apply if you were attempting to add a rule to e.g. Plus rather than Sup, yet your use of TagSetDelayed makes it clear that you are attaching the rule to Sup. ...


1

In this situation I might prefer to define this as a separate function. whatIsThis[x_Integer] := ToString[x] <> " is an Integer." whatIsThis[x_Real] := ToString[x] <> " is a Real." whatIsThis[x_] := ToString[x] <> " is something else." In[4]:= whatIsThis[4] Out[4]= "4 is an Integer." In[5]:= whatIsThis[4.1] Out[5]= "4.1 is a Real." ...


0

I may be off the mark by not making nested compositions. So, for what it's worth: pref[list_] := (f[m_] := m[[1 ;; #]] & /@ Range[Length@m]; g[t_] := Rule @@@ Partition[t, 2, 1]; Module[{str = {StartOfString, ##, EndOfString} & @@@ (Characters /@ list)}, TreePlot[Union[Flatten[g /@ (f /@ str)]], Automatic, {StartOfString}, ...


7

The observed behaviour will appear in any expression whose symbolic head has the attribute Flat. Under normal circumstances, with no attributes in play, we see the usual expected behaviour: MatchQ[f[1], f[1]] (* True *) MatchQ[f[1], f[a_]] (* True *) MatchQ[f[1], f[f[1]]] (* False *) MatchQ[f[1], f[f[a_]]] (* False *) ...


2

Times has attributes Flat, Orderless, and OneIdentity to cater for Associativity and Commutativity. These attributes affect patterns; in your case to ensure that x_.y_.z_ not only matches the pattern x, but also y and z. This is in line with the commutative property of multiplication.


2

Using a recursive Query: byPrefixTree = Query[{ Query[Select[# != {} &] /* GroupBy[First], All, Rest], Query[Select[# == {} &]]}] /* Merge[Join] /* Query[All, First, byPrefixTree[#] &]; Can be used directly to reconstruct a directory tree from FileNames[...,Infinity]. Can it be optimized? ~1000 files nested up to 15 folders ...


1

You can directly set a list of replacement rules as Downvalues of your Symbol in the order you prefer: DownValues[nonCommute] = {HoldPattern@nonCommute[left___, x_, x_, right___] :> f0[(*...*)], HoldPattern@nonCommute[left___, x_, a1_, x_, right___] :> f1[(*...*)], HoldPattern@nonCommute[left___, x_, a1_, a2_, x_, right___] :> ...


2

Yes it is certainly possible to tell the pattern matcher to search for the shortest pattern. rule = nonCommute[left___, x_, Shortest[middle__], x_, right___] :> {middle}; nonCommute[a, b, q, b, a] /. rule results in {q} and nonCommute[a, b, q, q, b, a] /. rule results in {q,q} but you should be somewhat cautious because that does not result in {} ...


3

Regular expressions are cryptic, but they offer look-ahead and look-behind capabilities that are unavailable to regular string patterns: split[s_] := StringSplit[s, RegularExpression["( |,|(?<![[:alpha:]])[-.]|[-.](?![[:alpha:]]))+"]] split[",,temp sp.a tiral - dump NV-A rambo.6833. 16,rgcht"] (* {"temp", "sp.a", "tiral", "dump", "NV-A", "rambo", ...


1

trialtext = ",,temp sp.a tiral - dump NV-A rambo.6833. 16,rgcht"; StringTrim@StringSplit[trialtext, {"," | "-" | ".", x : PatternSequence[Except[WhitespaceCharacter] .. ~~ "." | "-" ~~LetterCharacter ..] :> x}] (* {"temp", "sp.a", "tiral", "dump", "NV-A", "rambo", "6833", "16", "rgcht"} *)


1

... If your list list={1,1,1,1,0,0,0,1,1,1}; was a String : mystring = (StringJoin @@ ToString /@ list) (* 1111000111 *) you could also do : StringCases[mystring, s : (StartOfString ~~ (x_) ..) :> StringLength@s][[1]] (* 4 *) or StringPosition[mystring, (StartOfString ~~ (x_) ..)][[1, -1]] (* 4 *) It is also fast because it just searchs the ...


5

Regarding the updated description of your problem while Split is very clean it is not optimal unless the overall list is relatively short. As an example consider this data: SeedRandom[0]; a = RandomChoice[{"a", "b", "c"}, 1*^7]; It begins with: {"c", "c", "b", "a", . . .} The method from your answer takes significant time: Needs["GeneralUtilities`"] ...


1

I want to thank everybody for their answers! I wanted to post an answer I saw in another question here on MSE but I can't seem to find it right now, but this was the solution that worked the simplest: Length[Split[LIST][[1]]] So Using Split partitions the list as I wanted, and then I can just take the first element of that partitioned list, and find the ...


3

l = {0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1} LengthWhile[l[[LengthWhile[l, # != 1 &] + 1 ;;]], # == 1 &] (* 4 *) Edit: and this is dedicated to that special person: k = LengthWhile; l[[l~k~(# != 1 &) + 1 ;;]]~k~(# == 1 &) (* 4 *)


2

For what it's worth, a much better pattern (time complexity of order n instead of n^2), but still with a similar problem that Mr. Wizard pointed out. It is perhaps interesting to wonder about the difference between these two patterns. Replace[list, {x__, Except[First[list]], ___} :> Length[{x}]] /. y_List :> Length[y] First version (time complexity ...


1

Update 2: Based on OP's latest clarification: lfF = With[{x = First@#}, LengthWhile[#, # == x &]] & lfF@{1, 1, 1, 1, 0, 0, 0, 1, 1, 1} (* 4 *) lfF@{0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1} (* 2 *) or lfF2 = Length@First@Split@# &; lfF2@{1, 1, 1, 1, 0, 0, 0, 1, 1, 1} (* 4 *) lfF2@{0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1} (* 2*) Update: Per ...


1

ClearAll[f, g, q1, q2, q3, d, k1, k2] your list: flist = {f[q1, q2], f[q3, q4], g[q1], g[q2, q3, q4], d[k1 - q1], d[k2 - q2 - q3 - q4]} First set of rules Without repeated rules Make a list of all possible combinations of f[_] and g[_] using Tuples, then Select the ones with IntersectingQ arguments, and change Head from List to Rule using Apply (@@, ...


5

Whenever you run into unexpected results with pattern matching you need to consider how the pattern object itself evaluates. For example consider these: Plus[__] Plus[_, _] Times[_, _] __ 2 _ _^2 And now your pattern: Hypergeometric2F1[_, _, _, _] (1 - _)^-_ To prevent this evaluation you can use either HoldPattern or Verbatim: ...



Top 50 recent answers are included