Hot answers tagged

43

I think Leonid's answer deserves to be expanded upon. Most other languages are not symbolic, and thus the "variable name" is not something one needs to keep track of --- ultimately the interpreted or compiled code is keeping track of pointers or something. In contrast, in Mathematica the Head of an expression is arbitrary. This is somewhat along the lines ...


33

I am pretty sure that it is not the best solution but how about this? numbering[x_] := Block[{n = 0}, Replace[x, y_ :> {++n, y}, {-1}]] Some example outputs: In[1]:= numbering[{a, b, {c, d}, e, {f, {g, h}}}] Out[1]= {{1, a}, {2, b}, {{3, c}, {4, d}}, {5, e}, {{6, f}, {{7, g}, {8, h}}}} In[2]:= numbering[Nest[{#, #} &, x, 3]] Out[2]= {{{{1, x}, {...


32

General usage Here is what I think Using strings and subsequently ToString - ToExpression just to generate variable names is pretty much unacceptable, or at the very least should be the last thing you try. I don't know of a single case where this couldn't be replaced with a better solution Using subscripts is also pretty bad and should be avoided, except ...


22

This is the same basic method as already presented by Yu-Sung Chang, but Map is more concise. More significantly using Block is incorrect: if n appears in the input it will be incorrectly substituted. Instead I would write: expr = {a, b, {c, d}, e, {f, {g, h}}}; Module[{i = 1}, Map[{i++, #} &, expr, {-1}] ] {{1, a}, {2, b}, {{3, c}, {4, d}}, {5, ...


21

My answer is based on a modification of a binary heap. Basically the construction looks something like this. We start with a binary tree: Notice that if we label the nodes breadth-first, the labels have an interesting property. Each parent node $n$ has two children, $2n$ and $2n+1$. This also works in reverse: the parent of node $n$ is node $\left\...


18

we can also use the Listable attribute of Function: i = 1; Function[, {i++, #}, Listable]@{a, b, {c, d}, e, {f, {g, h}}} or(just to explore the Listable nature): i = 1; Function[, {##}, Listable][i++//Unevaluated, {a, b, {c, d}, e, {f, {g, h}}}] output: {{1, a}, {2, b}, {{3, c}, {4, d}}, {5, e}, {{6, f}, {{7, g}, {8, h}}}}


17

Preface Below, you will find two different solutions. For understanding the problem itself, the first, iterative solution is better suited since it gives insight in how the solution can be found without directly executing the instructions given as input. Iterative Solution Detailed explanation To explain the idea behind this approach let us work with a ...


15

Many index-specific operations can be implemented via MapIndexed with a level specificaton. Your Power example can be written as: MapIndexed[#1^(#2[[1]]*#2[[2]]) &, test2D, {2}] If you want better readability of indices you can define an auxiliary function: myPower[x_, {n1_, n2_}] := x^(n1 n2); MapIndexed[myPower, test2D, {2}] Some index-specific ...


14

With ReplaceAll and Increment you can do it: i = 1; {a, b, {c, d}, e, {f, {g, h}}} /. p : Except[List]?AtomQ :> {i++, p} {{1, a}, {2, b}, {{3, c}, {4, d}}, {5, e}, {{6, f}, {{7, g}, {8, h}}}} This works if a, b, etc are simple symbols... maybe is not what you need.


13

I have a tree-based method that has the right asymptotics but a very high coefficient. The upshot being, it will not compete with other methods until we get past 10^6 or so in list size. With considerable work that tree structure could be flattened so that Compile might be brought into play. The basic tree layout is {left subtree, node, right subtree} where ...


13

I will use big and small rather than bigList and smallList, for brevity. As stated by others if you can select the positions at random in the first place this will be faster, e.g.: pos = RandomSample[Range @ Length @ big, 1200]; You can then get the small list with: small = big[[pos]]. To carry out the specific operation you describe the key detail will ...


13

I've never had a need for the MapAll (or //@) function, but this seems to be a case where it can be used: i=0; f[x_Symbol] := {++i, x}; f[x_List] := x f //@ {a, b, {c, d}, e, {f, {g, h}}} (* {{1, a}, {2, b}, {{3, c}, {4, d}}, {5, e}, {{6, f}, {{7, g}, {8, h}}}} *)


12

Some years ago, a friend of mine was in the supermarket with his son, small kid, who asked him to buy some candy. After some resistance, my friend agreed, but told him that should be just one. In the cashier, his son had two candy, and my friend said: What is this? haven't we agreed One? And the answer (very smart) was: Yes! Here it is. Zero and One... (...


12

I don't know if this is useful to you but it seems a little cleaner than your own code: asc = <|"z" -> 11, "x" -> 22, "b" -> 33, "a" -> 44|>; keySpan[k_Span][asc_Association] := asc[[k /. First /@ PositionIndex@Keys@asc]] asc // keySpan["x" ;; "a"] asc // keySpan["z" ;; "a" ;; 2] asc // keySpan["b" ;;] <|"x" -> 22, "b" -> 33,...


11

It's a little on the hairy side, but you can do it functionally (i.e., without mutating a counter) by first finding all the leaves using Position, and then replacing what you find at those positions one by one using Fold: tree = {a, b, {c, d}, e, {f, {g, h}}}; Module[{indexLeaf}, With[{indexedPositions = Transpose[ {Range@Length@#, #}] &@...


11

I think you may merely want MapIndexed. For your first example: lst = {{"X", {{"X", "X"}, {{"X", "X"}, "X"}, "X"}, "X"}, "X", "X"}; f[s_String, pos_] := {Length@pos, s} f[other_, _] := other MapIndexed[f, lst, -1] {{{2,"X"},{{{4,"X"},{4,"X"}},{{{5,"X"},{5,"X"}},{4,"X"}},{3,"X"}},{2,"X"}},{1,"X"},{1,"X"}} Alternatively, your own formulation may be ...


11

MapIndexed: MapIndexed[#2[[1]] + # &, {a, b, c, d}] {1 + a, 2 + b, 3 + c, 4 + d} Also Range[Length @ #] + # & @ {a,b,c,d} {1 + a, 2 + b, 3 + c, 4 + d}


10

My goal is to add an index to all elements of a list in the form {"a", "b", "c", ... }, so it becomes {"N1 a", "N2 b", "N3 c" ... } may be seq={"a","b","c","d"}; MapIndexed["N"<>ToString[First@#2]<>" "<>#1&,seq] gives {"N1 a", "N2 b", "N3 c", "N4 d"}


9

Perhaps Module[{k = 0}, Replace[{a, b, {c, d}, e, {f, {g, h}}} , i_ :> With[{index = ++k}, {i, index}/;True], {-1}]] {{a, 1}, {b, 2}, {{c, 3}, {d, 4}}, {e, 5}, {{f, 6}, {{g, 7}, {h, 8}}}}


9

strs = {"first block of text with random content", "different block of text", "1 2 3 4"}; Nearest[(StringPadRight[#, 50] & /@ strs), "content random with"] This is a deep and complex question apparently: Mathematica has a menagerie of built in goodies to assemble your own variant. EditDistance DamerauLevenshteinDistance ...


9

As of Mathematica 11: filenames = Table[CreateFile[], 3]; content = {"first block of text with random content", "different block of text", "1 2 3 4"}; MapThread[Put, {content, filenames}]; index = CreateSearchIndex[filenames]; Perform searches using TextSearch: Snippet /@ Normal@TextSearch[index, "block"] In order to rank search results, score them ...


9

If you put your cursor on the Position command and press F1 for help, you will see the following under Properties and Relations: "Use Extract to extract parts based on results from Position." There is also an example. For your case: p = Position[{a, b, c, d, e, f}, c] Extract[list,p] where list is the list you want to extract from.


9

We don't need to avoid Table in my view. In cases that Table is more straightforward, just use Table. If speed is concerned, Compile it. Here is an example: Can I generate a "piecewise" list from a list in a fast and elegant way? Nevertheless, your 2 examples (especially 2nd one) don't belong to the cases that Table is more straightforward, at ...


7

Using DownValues enables you to format the display in the subscripted form without using Notation and Symbolize (Format[#[n_]] := Subscript[#, n]) & /@ {x, σ, a}; kvar[k_] := Through[{x, σ, a}[k]] kvar[3] kvar[n] If you will never use a symbolic index then you can restrict the argument of kvar to Integer as you did originally.


7

func1[a_, b_] := a + b; func2[a_, b_] := 1 + a + b; func3[a_, b_] := a + 2 b; n = 10; sa = SparseArray[{Band[{1, 1}] -> (func1[0, #] & /@ Range[n]), Band[{1, 2}] -> (func2[0, #] & /@ Range[n - 1]), Band[{2, 1}] -> (func3[0, #] & /@ Range[n - 1])}, {n, n}]; sa // MatrixForm or sa = Quiet@SparseArray[{Band[{1, 1}] -> (...


7

Try Pick[foo, mask] (* {a, c}*)


6

Prompted by comments conversation with Mr. Wizard, a routine I use: findMultiPosXX[list_, find_, allowBits_: False, skipCands_: True] := Module[{f = DeleteDuplicates[find], o, l, oo, bitmax = 20, cands, dims}, If[allowBits && Length@f <= bitmax, With[{r = If[Length@(dims = Dimensions@list) == 1, Range@Length@list, Array[...


6

lst = {{"X", {{"X", "X"}, {{"X", "X"}, "X"}, "X"}, "X"}, "X", "X"}; SetAttributes[f, Listable] Map[f, lst, {1, Infinity}]; ClearAttributes[f, Listable] %% //. { f[x_String] :> {1, x}, f[{i_Integer, x_String}] :> {i + 1, x}} {{{2, "X"}, {{{4, "X"}, {4, "X"}}, {{{5, "X"}, {5, "X"}}, {4, "X"}}, {3, "X"}}, {2, "X"}}, {1, "X"}, {1, "X"}}


6

This obviously can't hold a candle to Mr. Wizard's solutions, and is a bit hackish as well, but anyway: Fold[Replace[#1, "X" -> {#2, "A"}, {#2}] &, lst, Range[Depth[lst] - 1]] /. "A" -> "X" If there's anyway to use this approach without using the dummy symbol, I'd like to know about it. -> Edit: See Mr. Wizard's solution in the comments.


6

Module[{p = Range[Length@#]}, Reap@Fold[(Sow[#[[#2]]]; Drop[#, {#2}]) &, p, #]] &@{1, 1, 2, 1, 1} (* {{}, {{1, 2, 4, 3, 5}}} *)


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