Tag Info

New answers tagged

9

Unless both lists given to Equal are packed arrays Equal will first unpack. Unfortunately for this case {} is not a packable expression, therefore list == {} will always unpack list, assuming it starts packed. That unpacking takes time: test = RandomInteger[100000000, 10000000]; Developer`FromPackedArray[test]; // AbsoluteTiming {0.207012, Null} ...


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; ...


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...): (* ...


1

f[x_] := Plus @@ (Join[x, {0, 0}] /. {___, 0, r__} :> {r}) == 0 f /@ {{0, 1, 2, 3, 0}, {1, 2, 3, 0, 0, 0}, {0, 0, 1, 2, 3}} (* {False, True, False} *) SeedRandom[0] x = RandomInteger[999, 20000]; f@x // Timing // First (* 0. *)


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} *)


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) ...}; ...


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 &



Top 50 recent answers are included