Tag Info

Hot answers tagged

11

The behaviour we are seeing is due to an up-value on Dataset. Many operators have special meaning when applied to Dataset. They are typically changed so that they operate upon the content of the dataset and then wrap the result back into a dataset. ReplaceAll is one of those operators. We can see that this special behaviour is implemented as an up-value ...


8

As others have indicated this result is not surprising at all. What you actually need is not StringReplace but ReplaceAll (/.): {"90", "", "20"} /. "" -> "0" {"90", "0", "20"}


7

Your pattern has itself in its own definition. Mathematica will keep substituting the definition in at each level until it runs out of stack. From this answer about recursive string matching we can see a potential solution: using MatchQ instead of the explicit pattern, since Condition will prevent the recursive part of the pattern from being evaluated when ...


7

Here is how I would do it: expr = 1/((x + a + b) (c + d)); Limit[ ϵ expr /. Thread[# -> ϵ #] &@Select[Variables[expr], # =!= x &], ϵ -> 0 ] (* ==> 1/(c x + d x) *) I replaced all variables except x by ϵ times themselves and took the limit of ϵ times the original expression as ϵ goes to zero. This will leave only terms linear in the ...


7

Finally: test5 = OrderedQ @ Reverse @ Unitize @ # & slow stuff: test = MatchQ[#, {Except[0] .., (0) ...}] & new one, this is "only" two orders of magnitude slower than Mr.Wizard's :) test3 = Length[Split[#, Count[{##}, 0] != 1 &]] <= 2 & getting closer, only twice as long: test4 = Length @ Split @ Unitize @ # <= 2 &


7

The illustrated behavior seems reasonable to me, even if it may not seem "natural." For position or replacement a given pattern should match when it appears between any two sequences of characters, or it is at the beginning and end of a string. A zero-length string effectively is between every pair of characters. Why should it not match? To keep it from ...


7

General Dataset has been internally overloaded on many system functions via UpValues. This is necessary to make sure that those functions work on Dataset properly, and this behavior may not be the same as would've been by default (without such redefinitions). However, in some cases, this might not be desirable. Below is the code that I suggest to use to ...


6

The first pattern that came to mind: p1 = {___, 0, Except[0], ___}; ! MatchQ[{2, 3, 17}, p1] ! MatchQ[{2, 3, 17, 0, 0}, p1] ! MatchQ[{1, 0, 1, 0, 1}, p1] True True False I am exploring other avenues now. It seems that this pattern is vastly more efficient that Kuba's superficially similar one. As a simple example: pK = {Except[0] .., (0) ...}; ...


5

For big collections of lists, this should be quick: fx = With[{s = SparseArray[PadRight@#]["AdjacencyLists"]}, SameQ @@@ Transpose[{Length /@ s, Last /@ Replace[s, {} -> {0}, 1]}]] &; Update: Even more so: fx2 = OrderedQ /@ Unitize[#[[All, -1 ;; 1 ;; -1]]] &; Compare (old netbook timings... seems to clobber other answers so far...): (* ...


5

I'm not sure about general way, are you concerned of keeping thing unevaluated for example? Are there any Locked heads? Based on Szabolcs suggestion: test = SameQ @@ (Sort //@ {##})& test[ h1[1, h2[3, 2]], h1[h2[2, 3], 1] ] True Or faster modyfication: ord[h_[x__]] := h @@ Sort[{x}]; ord[x___] := x SameQ @@ (ord //@ {h1[h2[2, 3], 1], ...


5

That is a rather slippery replacement, "Find nothing and replace it with something" Try telling the replacement that there nothing between the beginning and end StringReplace[{"90", "", "20"}, {StartOfString ~~ "" ~~ EndOfString -> "0"}]


4

I don't know why Exp[2 I u Sin[x]] /. Exp[Complex[0, a_] u Sin[x]] :> a doesn't work as expected, except that MatchQ[Exp[2 I u Sin[x]], Exp[Complex[0, a_] u Sin[x]]] gives False However, since the apparently more general MatchQ[Exp[2 I u Sin[x]], Exp[Complex[0, a_] u_ v_]] gives True you could use Exp[2 I u Sin[x]] /. Exp[Complex[0, ...


4

The answer has to do with the difference between Rule(->) and RuleDelayed(:>): Rule: h = h1 /. Derivative[q_, r_][p][x, v] -> dpdx[q + 2*r]/(2^r) RuleDelayed: h = h1 /. Derivative[q_, r_][p][x, v] :> dpdx[q + 2*r]/(2^r) Rule a -> b first evaluates the expression b and then replaces a with b. RuleDelayed a :> b first replaces a with b, ...


4

Using RuleDelayed instead of Rule in ReplacePart: ReplacePart[a, {i_, i_} :> 2 a[[i, i]]] or, using Part assignment as in: (a[[#, #]] = 2 a[[#, #]]) & /@ Range[3] Table[a[[i, i]] == 2 a[[i, i]], {i, 1, 3}] or, using MapAt: MapAt[2 # &, a, Table[{j, j}, {j, 3}]] or, using MapIndexed: MapIndexed[If[SameQ @@ #2, 2 #, #] &, a, {2}] (* ...


4

Your pattern matches <nothing><a><bcdef> so the a is replaced with 1. Next pass, the pattern matches <nothing><1><bcdef>, since replacement would result in no change, replacement stops. It's not clear from the OP in its current state what it is you want to accomplish. Add that info, and you'll surely get responses. It ...


3

If I understand the intent correctly, then the following definitions should recognize valid forms: ClearAll[formQ, listQ, atomQ, sequenceQ] formQ[x___] := listQ[x] || atomQ[x] atomQ[token[Except["("|")"]]] := True atomQ[___] := False listQ[token["("], x___, token[")"]] := sequenceQ[x] listQ[___] := False sequenceQ[] := True sequenceQ[x__ /; formQ[x], ...


3

I have trouble following your example (in the comment) so I shall attempt to answer this question generically. If you can give a few examples of actual input and output that you expect from listQ I shall attempt to implement it. Individual elements of of pattern sequence are tested when you use PatternTest, but the entire sequence can be easily tested if ...


3

This seems like a bug. Additional examples that would need to be explained if it is not: foo[2 I u Sin[x]] /. foo[Complex[0, _] u Sin[x]] :> bar foo[2 I u Sin[x]] /. foo[Complex[0, _] (p : u) Sin[x]] :> bar foo[2 I u Sin[x]] /. foo[Complex[0, _] HoldPattern[u] Sin[x]] :> bar foo[2 I u Sin[x]] bar bar So the problem is unrelated to ...


3

rules = {runBool -> True, linearBool -> True, ab -> 3, linx -> 10}; FilterRules[rules, _?(StringMatchQ[ToString[#], "lin*"] &)] (*{linearBool -> True, linx -> 10}*)


3

rules = {runBool -> True, linearBool -> True, ab -> 3, linx -> 10}; FilterRules[rules, x_ /; With[{z = ToString@x}, StringLength@z >= 3 && StringTake[z, 3] == "lin"]] (* {linearBool -> True, linx -> 10} *) But something like Pick[rules, StringMatchQ[ToString /@ rules[[All, 1]], "lin*"]] is cleaner, IMO, and allows ...


3

Assuming you have typed fit = NonlinearModelFit[{{0, 1}, {1, 2}, {3, 3}}, a + b*x, {a, b}, x] Using this great answer you can type StringProperties[NonlinearModelFit] ...


2

I appreciate Jens's answer. However I want to answer literally For example, a sum of several fractions of this form would require isolation of each fraction first, then pattern replacement, then reconstruction of the full expression. Is there a more efficent and general method for this type of replacement/pattern matching? Here are nice functions ...


2

expr = 1/((x + a + b) (c + d)); Based on clipping by total degree. Let me make this answer more general. ClearAll@expand Options[expand] = {"SmallTerms" -> Automatic, "Order" -> 1, "Except" -> {}}; expand[expr_, OptionsPattern[]] := Module[{ t, vars = Fold[ DeleteCases, Flatten[{OptionValue["SmallTerms"]} /. Automatic -> ...


2

expr = Series[E^(x/v), {v, Infinity, 3}] // Normal; (* gen some Ds *) t = Table[Assuming[j ∈ Integers, D[expr, {v, j}]], {j, 1, 10}]; (* get the pattern...*) seq = FindSequenceFunction[t /. v -> 1, FunctionSpace -> All] (* spot check some results...*) yours = (-1)^j*(j! x + (j + 1)! (x^2)/2 + (j + 2)!*(x^3)/12); SameQ @@@ Table[{yours /. j -> z, ...


2

ClearAll[f1,f2] f1 = With[{u = Unitize@#}, FreeQ[u[[;; Tr@u]], 0]] &; f1 /@ {{1, 2, 3}, {0, 1, 2, 3, 0}, {1, 2, 3, 0, 0, 0}, {0, 0, 1, 2, 3}} (* {True, False, True, False} *) f2 = With[{u = Unitize@#}, Times @@ N @ u[[;; Tr@u]] != 0] &; f2 /@ {{1, 2, 3}, {0, 1, 2, 3, 0}, {1, 2, 3, 0, 0, 0}, {0, 0, 1, 2, 3}} (* {True, False, True, False} *)


2

a = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} f = # + #*IdentityMatrix[Dimensions@#] &; f@a (* {{2, 2, 3}, {4, 10, 6}, {7, 8, 18}} *)


2

Here are two bulky yet fast compiled functions. The two functions are essentially the same, but the second one is slightly adapted to rashers test case for timing comparisons. In my previous version they were even longer, but it turns out they are faster this way. cfu = Compile[ {{ints, _Integer, 1}} , Block[ {len, zFlag, res} , res = True; ...


2

Ditto what Kuba said about details. Another guess: expr /. Thread[Variables[expr] -> 1] (* 6 *) I guess it works for polynomials. It's not really clear to me what the coefficients of Exp[x] are. (It might be 1 Exp[1 x], etc.) Or (x + y)^2 vs. x^2 + 2 x y + y^2. (This answer gives the sum of the coefficients of the latter.) Another ...


2

It appears that the BlankNullSequence defaults to matching zero arguments, if possible. Try this: {a, b, c, d, e, f} //. {x__, y___} :> {y, 1} {1,1,1,1,1,1}


2

It does what it is designt to, so either put there a stronger pattern: Flatten @ StringCases[list, StartOfString ~~ "H" ~~ __ ~~ EndOfString] or use more suited functions: Select[list, StringMatchQ[#, "H" ~~ __] &]



Only top voted, non community-wiki answers of a minimum length are eligible