Tag Info

Hot answers tagged

15

Rather than it being "too big" for the pattern matcher, the problem here is because of the use of //. which applies the rule repeatedly till the result no longer changes (i.e. the list is sorted). In other words, the issue is that of the complexity of the algorithm you're using (//. with ___) rather than the programming paradigm that you've chosen (pattern ...


13

You can use ReplaceList with a helper function which has the Orderless attribute: ClearAll[f]; SetAttributes[f, Orderless]; ReplaceList[f[a, b, c], f[a___, b___, c___] :> {{a}, {b}, {c}}] // DeleteCases[#, {}, -1] & // Union // Column The DeleteCases and Union are required because the output from ReplaceList includes the empty list {} as a ...


10

SeedRandom[42]; haystack = RandomReal[1, 6300]; AbsoluteTiming[ f = Nearest[haystack -> Range@Length@haystack]; {f[.3, 1], haystack[[f[.3, 1]]]}] (* -> {0.015625, {{3123}, {0.300033}}} *) Of course in this case most of the time is expended calculating the nearest function. If your points aren't changing from one use to the next, the time for ...


9

Leonid Shifrin has pointed out why the 3rd sample fails: Less doesn't "compare" strings. Still, it's possible to use Sort, with the addition of OrderedQ: Sort[list, OrderedQ[{#1[[2]], #2[[2]]}] &] {{4, "a"}, {9, "b"}, {6, "k3"}, {7, "k4"}, {5, "w"}}


8

Using Mathematica 7: Needs["Combinatorica`"] Partition[Flatten@ExtractCycles@FromUnorderedPairs@list, 2, 1] => {{140, 1}, {1, 2}, {2, 43}, {43, 10}, {10, 140}} Edit testLalmei = RandomSample /@ (RandomSample@ Partition[RandomInteger[{1, 1000}, 100], 2, 1, -1]); ExtractCycles@FromUnorderedPairs@testLalmei => { {643, 115, 518, 238, ...


7

I'm always afraid in case of list-manipulation that there was a duplicate in the past. But I do not remember. You can try this: Extract[list, Position[labels, #]] & /@ Union@labels {{{1 ,2}, {-3, 4}, {-9, 1}}, {{5, 6}, {7, 8}}, {{-1, 3}, {0, 1}}} and this: Pick[list, labels, #] & /@ Union@labels {{{1, 2}, {-3, 4}, {-9, 1}}, {{5, 6}, ...


6

Revised answer For the true meaning of the question as it has now been clarified: I do not believe you are likely to be able to greatly improve over Complement as I believe the sort is not superfluous but rather an integral part of the algorithm. I can only offer my orderedComplement without the pre-processing; it may in some cases be faster as it uses ...


6

In your particular case, the following does the job: lst = {{1, 2}, {10, 140}, {43, 10}, {1, 140}, {43, 2}}; List @@@ If[# === {}, {}, First[#]] &[FindHamiltonianCycle[Graph[UndirectedEdge @@@ lst]]] (* {{1, 2}, {2, 43}, {43, 10}, {10, 140}, {140, 1}} *) To work for your larger test, it should be generated by a variation of your code: test = ...


6

As L.S. said, using MMA like C is a path to poor performance. Based on the OP content, I took the liberty of assuming you want the Mean of remaining tuple values appended to the first: d = {{1, 2}, {1, 3}, {3, 4}, {5, 1}, {6, 9}, {6, 8}, {6, 1}}; Map[{#[[1, 1]], Mean[#[[All, 2]]]} &, GatherBy[d, First]] test = RandomInteger[{1, 20}, {100000, 2}]; ...


5

You can do this in many ways. For example: SortBy[filenames, ToExpression@FileBaseName[#] &] Before @Leonid's comment I used StringDrop[FileNameTake[#], 4]& to get rid of ".tif". Now it is more general FileBaseName.


5

You can call the windows function that does the sorting directly. The function is StrCmpLogicalW. Note that this is not a cross-platform solution:) Here is a short example: Needs["NETLink`"]; naturalOrder = DefineDLLFunction["StrCmpLogicalW", "Shlwapi.dll", "int", {"string", "string"}, MarshalStringsAs -> "Unicode"]; strings = {"Ie501sp2", ...


5

Simon Woods already gave what is arguably the canonical answer, but I always like seeing and sharing alternatives. Since one of the operations here is a duplicate-removal we can adapt some of the methods described in Delete duplicate elements from a list. SeedRandom[3] a = RandomInteger[5, {9, 2}]; (* {{3, 5}, {0, 1}, {2, 0}, {0, 4}, {5, 2}, {2, 2}, {1, ...


5

I believe the best way is to use an Ordering function with recognition of duplicates. Please see that (self) Q&A for an explanation. myOrdering[a_List] := GatherBy[Ordering@a, a[[#]] &] list[[#]] & /@ myOrdering[labels] {{{1, 2}, {-3, 4}, {-9, 1}}, {{5, 6}, {7, 8}}, {{-1, 3}, {0, 1}}} Timings Here are timings of each of the methods ...


5

My GatherBy variation: GatherBy[Transpose@{labels, list}, First][[All, All, 2]] {{{1, 2}, {-3, 4}, {-9, 1}}, {{-1, 3}, {0, 1}}, {{5, 6}, {7, 8}}} A possible drawback is that the result is not sorted by label. This is easy to change by doing GatherBy[Sort@Transpose@{labels, list}, First][[All, All, 2]] {{{-9, 1}, {-3, 4}, {1, 2}}, {{5, 6}, {7, ...


5

Don't compare values that are likely to be infinities. Instead, compute Limit on ratios of arguments to be sorted: Sort[v, Limit[#1 / #2, n -> Infinity] < 1 &] You need to use valid functions, though; whatever Iteratedlog is, it's going to be nonsensical on this comparison as it's not defined. Mathematica silently skips complaining about it, ...


4

I believe you can effect any of the lex, colex, revlex, revcolex sorts by reversing elements and lists in the proper sequence. Edit: My original answer used Sort and Reverse. Since at the moment I cannot see why I did not use SortBy[x, Reverse] as Simon Woods did in an answer to a similar question I am modifying my answer to use the simpler method. ...


4

One way is to use the optional second argument of Union, which specifies what elements are to be considered the same. This tests to see if the second elements are less than 10^-4 apart, and then sorts the results. union = Union[list, SameTest -> (Abs[#1[[2]] - #2[[2]]] < 10^-4 &)]; SortBy[union, #[[2]] &] {{c, 3}, {b, 3.04}, {a, 3.1}} ...


4

m = {"computer", "экзамен", "elephant", "стол", "bread", "телефон", "exception", "desktop", "best", "колонка", "zoom", "saphire", "ярость"}; First Sort it: sortedm = SortBy[m, First@ToCharacterCode@# &] {"best", "bread", "computer", "desktop", "elephant", "exception", "saphire", "zoom", "колонка", "стол", "телефон", "экзамен", "ярость"} ...


4

{ First @ First @ #, Mean @ Last @ Transpose @ #}& /@ GatherBy[ M, First] {{1, 5/2}, {3, 4}, {5, 1}, {6, 6}} or {First @ #1, Mean @ #2}& @@@ Transpose /@ GatherBy[ M, First] See (Apply (at the first level) - @@@, Map - /@, Slot - #)


4

The function Less is what you can use. list = {2 Pi - 2 ArcTan[Sqrt[2 + Sqrt[5]]], 2 ArcTan[Sqrt[2 + Sqrt[5]]], 2 Pi + 2 ArcTan[Sqrt[2 + Sqrt[5]]]}; Sort[list, Less] Or, Sort[list, #1 < #2 &] Or you could use: SortBy[list, N@# &]


3

I briefly closed this question, then realized I had more to say than easily fits into the comments. This is documented behavior so in a way you have to learn to live with it, but the work-around is very simple: use SortBy SortBy[{13, Sqrt[157], Sqrt[163]}, N] {Sqrt[157], Sqrt[163], 13} This is far superior to using Sort with a second argument as it ...


3

[Warning: There could be issues with the averaging procedure. At least one should pay attention to allPossibleOrderings; its definition probably needs to be improved. See other two *edit*s in text below.] I'm probably doing something nasty here but if RAM is really not a problem for you, then… here you go, a blunt brute-force approach: KemenyDistance = ...


3

Ahh good fun questions. Anyway this isn't a comprehensive answer but rather just a quick test on the basics: list = {0.1, I, 2 + I, 0, 2 , 2 x, x, xxx, 2^x, x^2, x^x, x^ (2 x), X, xX, "y", "yy", "Y"}; Sort[list] {0, I, 0.1, 2, 2 + I, 2^x, "y", "Y", "yy", x, 2 x, x^2, x^x, x^( 2 x), X, xX, xxx} Only thing that grabs my attention is imaginary numbers ...


3

A 2D example of what i suggested in my comment: Based on Belisarius example..we get three lines obviously not connected properly: m = SparseArray[{i_, j_} -> Sin[i j 9 /10 y], {3, 3}]; alle = Table[Eigenvalues[m], {y, 0, 1, .1}]; original = Show[ MapIndexed[ListPlot[Flatten[Take[alle, All, {#}] , 2], Joined -> True, PlotRange -> All, ...


3

This is practically the same as Simon's solution, but it might be theoretically a bit more efficient: SplitBy[SortBy[list, Last], Last][[All, 1]] This is in fact what people used when Gather/GatherBy were not yet available. I believe SplitBy can be theoretically more efficient than GatherBy, but I have not benchmarked if this is indeed the case for the ...


3

You can use Ordering to get the new ordering of a and then rearrange both a and b accordingly: a = RandomComplex[1 + 1 I, {100, 1}]; b = RandomComplex[1 + 1 I, {100, 1}]; o = Ordering[a, All, Im[#1] < Im[#2] &]; sa = a[[o]]; sb = b[[o]];


3

Since you're using Mathematica 7, you could use DeleteDuplicates, it's what it was made for. SortBy[DeleteDuplicates[list, Last@#1 == Last@#2 &], Last] Though I personally like @Simon Woods's answer better, for elegance. Edit: to be clear, it sounds like you were only sorting as a prelude to a solution. If you don't actually need the sort, then it is ...


3

SortBy[{1 + I, 5 + I, what + I, 3 + 4 I, 5}, Re[#] &] {1+I,3+4 I,5,5+I,I+what} SortBy[{1 + I, 5 + I, what + I, 3 + 4 I, 5}, Re[#] &] // Reverse {I+what,5+I,5,3+4 I,1+I} SortBy[{1+I,5+I,what+I,3+4I,5},Im[#]&] {5,1+I,5+I,3+4 I,I+what} hehe! ...


3

I think that it can be done, without loading all the data into memory. The main idea would be to load only the data necessary to do the sorting and then take advantage of Stream Let's first create a a fake log file with random data: strW = OpenWrite["UnSorted.txt"] Do[ WriteString[strW, FromCharacterCode[RandomInteger[{65, 90}, 10]], "\t" , ...


2

If $ u $ is strictly increasing, then so is $ u^{-1}. $ You don't really care about their values so a representative of strictly increasing functions will preserve the ordering. $ y=x $ is such a function so I am replacing your u, u^(-1) with Identity and the ordering is the desired: CEs = {(u^(-1))[0.448165 u[10] + 0.551835 u[30]], (u^(-1))[ 0.296264 ...



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