Tag Info

Hot answers tagged

41

Point #1 Part always wraps element sequences with the original head of the expression. expr = Hold[1 + 1, 2 + 2, 3 + 3, 4 + 4, 5 + 5]; expr[[{2, 3}]] Hold[2 + 2, 3 + 3] For this purpose a single part e.g. 1 is not a sequence but {1} and 1 ;; 1 are: expr[[1]] expr[[{1}]] expr[[1 ;; 1]] 2 Hold[1 + 1] Hold[1 + 1] This applies at every level ...


34

You can use custom transformation rules, for example: -11 - 2 x + x^2 - 4 y + y^2 - 6 z + z^2 //. (a : _ : 1)*s_Symbol^2 + (b : _ : 1)*s_ + rest__ :> a (s + b/(2 a))^2 - b^2/(4 a) + rest returns (* -25 + (-1 + x)^2 + (-2 + y)^2 + (-3 + z)^2 *) The above rule does not account for cases where b is zero, but those are easy to add too, if ...


34

Generally, you want the Trott-Strzebonski in-place evaluation technique: In[47]:= f[x_Real]:=x^2; Hold[{Hold[2.],Hold[3.]}]/.n_Real:>With[{eval = f[n]},eval/;True] Out[48]= Hold[{Hold[4.],Hold[9.]}] It will inject the evaluated r.h.s. into an arbitrarily deep location in the held expression, where the expression was found that matched the rule ...


27

RuleCondition provides an undocumented, but very convenient, way to make replacements in held expressions. For example, if we want to square the odd integers in a held list: In[3]:= Hold[{1, 2, 3, 4, 5}] /. n_Integer :> RuleCondition[n^2, OddQ[n]] Out[3]= Hold[{1, 2, 9, 4, 25}] RuleCondition differs Condition in that the replacement expression is ...


18

That's an interesting first question. Welcome. :-) From a simplistic perspective this should work, but as you observe there are evaluation properties that are more complex. Here is a reference for most (but not all) behavior: The Standard Evaluation Sequence Let's follow those steps for your example. Heads are evaluated first Evaluate the head h of ...


17

I thought of this question while on the train but the solution appeared in my brain as soon as I got into work. All you need to do is create a ComplexityFunction that includes a side effect f[x_] := (Print[x]; LeafCount[x]) Simplify[TrigExpand[Tan[x + y]], ComplexityFunction -> f] This gives the following output (Cos[y] Sin[x])/(Cos[x] ...


17

The following seems to work, however I think it's not general enough: At a clean nb, enter: For[i = 0, i < 4, i++, Print[{i, {33, i}}]] For[i = 0, i < 4, i++, Print[Graphics[Circle[], ImageSize -> 20]]] And then retrieve the Print[ ] output as: c = Cases[NotebookRead /@ Cells[GeneratedCell -> True], Cell[___, "Print", ___]]; ToExpression ...


16

Implementation The following implementation is based on expression serialization and SequenceAlignment built-in function. The idea is to break expressions into constituent parts, then align these part sequences, and then determine the positions where the expressions are different. The auxiliary heads we will need are inert heads diff and myHold, the latter ...


14

Case #1 Observe: "anything" /. Plus[___] -> "match" "match" This is because Plus[___] evaluates to ___, and ___ matches anything. You can use HoldPattern: Sqrt[Plus[x, y]] /. HoldPattern[Plus[___]] -> u Sqrt[u] Case #2 You must understand that pattern matching is done on something close to the FullForm of an expression, rather than the ...


14

I assume you have Maple to use. If so, Simply open Maple and type the Mathematica command itself directly into Maple using the FromMma package built-into Maple, like this: restart; with(MmaTranslator); #load the package (*[FromMma, FromMmaNotebook, Mma, MmaToMaple]*) and now can use it FromMma(`Integrate[Cos[x],x]`); One can also use Maple convert ...


13

You may try for example something like: f[e_] := 100 Count[e, _Pochhammer, {0, Infinity}] + LeafCount[e]; FullSimplify[Pochhammer[k, n], ComplexityFunction -> f] (* ->Gamma[k + n]/Gamma[k] *)


13

#1 Trott-Strzebonski in-place evaluation: hf = HoldForm[1 - 1^2/2 + 1^3/3 - 1^4/4 + 1^5/5 - 1^6/6] hf /. x_Times :> With[{eval = x}, eval /; True] 1 - 1/2 + 1/3 - 1/4 + 1/5 - 1/6 Replace[hf, x_ :> With[{eval = x}, eval /; True], {2}] 1 - 1/2 + 1/3 - 1/4 + 1/5 - 1/6 One may simplify this method using the undocumented function ...


13

Distribute @ Sum[-2 Subscript[x, i] (-a Subscript[x, i] - b + Subscript[y, i]) // Expand, {i, n}] == 0


12

Perhaps only the developers (or Leonid) can answer #1 and #3 and "why". The quick answer to #2 is Apply, remembering that List is a Head like any other: List @@ (a + b + c) {a, b, c} On #3, I can't explain why ;; syntax gives 0 when (a + b + c)[[Range[0, 3]]] gives a + b + c + Plus So you could try List @@ ((a + b + c)[[Range[0, 3]]]) ...


11

Preamble After seeing no use of Mathematica (Code Jam Language Stats) in previous contests, I realized Mathematica is not allowed because there is no free version This is only to some point correct. Matlab is allowed too and is of course not free and very expensive. I was helping a friend of mine in round 2 and we weren't even close to good. Partly ...


11

Assuming you don't have any built-in symbols in that list, you could simply do: DeleteDuplicates@Cases[Leff, _Symbol, Infinity] (* {da, ma, dm, mc, La, h, R} *) If you do have symbols from built-in contexts or packages, you can simply pick out only those that are in the Global` context with: With[{globalQ = Context@# === "Global`" &}, ...


11

You can convert any expression to string by using ToString. If you want to preserve the visual representation, you should use ToString[(*your expression*), StandardForm]. logo = Import["http://wolfram.com/favicon.ico", "Image"] logostr = ToString[logo, StandardForm] StringJoin["Mathematica", logostr] % // StringQ Edit: By checking the cell expression ...


10

One way to induce Mathematica to simplify to Tan functions is to introduce the arguments as inverse tangents, as in $x\equiv \arctan a$ and $y\equiv \arctan b$. Then you could write for example Simplify[ TrigExpand@Tan[ArcTan[a] + ArcTan[b]]] /. {a -> Tan[x], b -> Tan[y]} (* ==> (Tan[x] + Tan[y])/(1 - Tan[x] Tan[y]) *) or more generally with ...


10

Here's one way to count the number of multiplications in an expression (equal to or greater than the number of Times in the expression). It should also work for several other binary operators, Listable or not (although I haven't tested it on them). t[x_, oper_: Times] := Tr @ ((Length[#] - 1) & /@ (Extract[x, {Sequence @@ Drop[#, ...


9

Here is a way to separate your equation into different subparts. It uses Reap and Sow to tag parts of the expression as either "equation" or "conditions" or "constants". f = Which[FreeQ[#, x], Sow[#, "constants"], MemberQ[{Equal, Unequal, Greater, GreaterEqual, Less, LessEqual, And, Or}, Head[#]], Sow[#, "conditions"],True, Sow[#, ...


9

This is a rather simple-minded approach, but maybe it will be useful to you: ClearAll[opCount]; opCount[h_, expr_] := Cases[ Hold[expr], HoldPattern@h[args : _ ~Repeated~ {2, Infinity}] :> Length@Hold[args] - 1, -2 ] // Total; SetAttributes[opCount, HoldRest]; Let's try: opCount[Times, 1*2*3*4*5 + 6*7*8] (* -> 6 *) opCount[Plus, 1*2*3*4*5 + ...


8

Since you get the result in terms of Piecewise, you can use things like Refine or Simplify, particularly when you want to get a result given some additional condition on your variables. In particular, Refine[PDF[LogNormalDistribution[1.75, 0.65], x], x > 0] (* ==> (0.613757 E^(-1.18343 (-1.75+Log[x])^2))/x *)


8

Perhaps you will find utility in Format and related functions? Unprotect[Pochhammer]; Format[Pochhammer[k_, n_]] := HoldForm[ Gamma[k + n]/Gamma[k] ] Protect[Pochhammer]; Pochhammer[a, b] Gamma[a + b]/Gamma[a] Similar things can be done with $PrePrint: $PrePrint = # /. Pochhammer[k_, n_] :> HoldForm[ Gamma[k + n]/Gamma[k] ] &; ...


8

Just do the ComplexExpand after the Conjugate ComplexExpand[Conjugate[I Cos[z] Sin[y] + Sin[z] + A (Cos[z] - I Sin[y] Sin[z])]] (* A Cos[z] + Sin[z] - I (Cos[z] Sin[y] - A Sin[y] Sin[z]) *)


8

For the first puzzle, I can only guess. The idea is that Function with named variables is a true lexical scoping construct, in that it cares about the possible name collisions inside the inner scoping constructs, including another Function-s (this is where it is different from Slot- based functions, which are not like that. The price to pay is that ...


8

Please let me know if this is moving in the right direction: expr = a + b*3*c + d; Replace[expr, h_[x___] :> {x}, {0, -1}] {a, {3, b, c}, d} Given that heads are lost here, perhaps you want something like: Replace[expr, h_[x___] :> {h, x}, {0, -1}] {Plus, a, {Times, 3, b, c}, d} If this is close to what you a related question that you ...


8

You can use Normal, ConditionalExpression is not explicitly mentioned there but documentation says it deals with special forms. p1 = y /. {First[Solve[x^2 + y^2 + x == 1, y, Reals]]} // First ConditionalExpression[-Sqrt[1 - x - x^2], 1/2 (-1 - Sqrt[5]) < x < 1/2 (-1 + Sqrt[5])] Normal @ p1 -Sqrt[1 - x - x^2]


8

I think you just need this: firstExternal[head_, expr_] := Module[{tag}, expr /. p_head :> Return[p, Module]] or perhaps, even much more elegantly: firstExternal[head_, expr_] := expr /. p_head :> Return[p, ReplaceAll] For example: firstExternal["Head of interest", deepExpression] (* "Head of interest"["This should be the first part of the ...


7

Two variants: (* left-associative *) Hold[a, Times, b, Plus, c, Subtract, f] //. f_[a_, p_, b_, c___] :> f[p[a, b], c] (* Hold[(a b + c) - f] *) (* right-associative *) Hold[a, Times, b, Plus, c, Subtract, f] //. f_[c___, a_, p_, b_] :> f[c, p[a, b]] (* Hold[a (b + (c - f))] *) after which one can apply ReleaseHold[]...



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