Tag Info

Hot answers tagged

8

Maybe this would help: list0[[;; Max[First /@ (Position[list0, #] & /@ targetList)]]] (*{54, 4, 7, 9, 3, 54, 4, 20, 2}*) In case targetList contains elements not in list0 then: (*Thanks to Chris Degnen*) list0[[;; Max[First /@ (Position[list0, #] & /@ Intersection[list0, targetList])]]]


8

What you face here is that you don't know how many values your result will have. There are two methods, that come instantly to my mind: The first one is to use Reap and Sow with a simple Do loop n = 20; Reap[Do[ If[Mod[i, 12] != 0 && ! IntegerQ[Sqrt[i]], Sow[i] ], {i, n}] ][[2, 1]] (* {2, 3, 5, 6, 7, 8, 10, 11, 13, 14, 15, 17, 18, 19, ...


5

This is an extended comment to halirutan's answer. I think you can get both speed and memory optimization for this problem. I made this a CW post because I used his code in his Q&A, Internal`Bag inside Compile, to remind myself how to use Internal`Bag, as well as some of his code from his answer to this question! myInts = Compile[{{n, _Integer}}, ...


5

As mentioned in the comment, you can try: Extract[y,x] or y[[Sequence @@ x]]


5

You might use Position pos = Position[toUpdate, 1] obtains, from toUpdate, the positions that you need to update and stores them in pos. Extract[newValues, pos] finds the values to be inserted. They are at the same positions in the list, newValues. ReplacePart inserts those values in the proper places--same positions, once again--in numbers. pos = ...


4

Because of lisatability of Iimes, Plus and Abs (see the Listable attribute and examine the full form of the underlying expression, moreover take a look at a fine structure of list addition in Mathematica e.g. Adding Lists Together) one can do simply this: numbers Abs[toUpdate - 1] + toUpdate newValues {{10, 2}, {3, 4}, {50, 60}} This solution ...


4

I propose: truncate[a_List, b_List] := a ~Take~ Max @ Lookup[PositionIndex[a][[All, 1]], b, 0] For maximum performance replace PositionIndex with cleanPosIdx from Why is the new PositionIndex horribly slow? I'll add comparative timings later if I get the chance.


3

(numbers[[##]]=newValues[[##]])&@@@Position[toUpdate,1]; (* thanks: Karsten7 *) numbers (* {{10,2},{3,4},{50,60}} *)



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