Tag Info

Hot answers tagged

25

As it happens there is a built-in function that already does this: Signature. If any two elements of list are the same, Signature[list] gives 0. dupeQ = 0 === Signature@# &; I believe this is the "canonical" answer. It is fast on both packed arrays and unpacked lists.


19

I usually use ToExpression["symbol", InputForm, ValueQ] ToExpression will wrap the result in its 3rd argument before evaluating it. Generally, all functions that extract parts (Extract, Level, etc.) have such an argument. This is useful when extracting parts of held expressions. ToExpression acts on strings or boxes, but both the problem with ...


18

Note: I am not particularly knowledgable in the field of this question, so what I write below may well be wrong. I don't know whether or not this should be considered a bug, but to my mind this is an instance of a clash of programming and mathematical functionality. To put it differently, predicates (functions ending with Q) seem to be a wrong match for ...


15

If there are repeated elements in the list, then calling Union[] on it will shorten it so that this element only appears once, so a simple implementation would be to test these lengths: test[list_] := Length[Union[list]] != Length[list] If you wanted to know which elements where repeated, you this could be accomplished by using Gather[] to collect ...


15

Because the assumption system is not called during the standard evaluation sequence, it is only called when Simplify, FullSimplify, Sum, Integrate etc... are used. Thus, x>0 remains unevaluated: Assuming[x > 0, x > 0] (* ==> x > 0 *) and TrueQ then returns False: Assuming[x > 0, TrueQ[x > 0]] (* ==> False *) If, however, you ...


15

Update: Internal`RealValuedNumericQ /@ {1, N[Pi], 1/2, Sin[1.], Pi, 3/4, aa, I} (* {True, True, True, True, True, True, False, False} *) or Internal`RealValuedNumberQ /@ {1, N[Pi], 1/2, Sin[1.], Pi, 3/4, aa, I} (* {True, True, True, True, False, True, False, False} *) Using @RM's test list listRM = With[{n = 10^5}, ...


15

As the responses show, there are a number of quick "probably real" tests. In general, the problem is undecidable, however. This is an easy corollary of Richardson's theorem, which says that it is impossible to decide if two real expressions $x$ and $y$ are equal. Assuming Richardson's theorem, note that $(x-y)i$ is real if and only if $x=y$. As a more ...


15

You have several options: foo[arg_?(VectorQ[#,NumericQ]&)] foo[arg: {_?NumericQ ..}] foo[arg: {__?NumericQ}] For matrices or higher dimensional arrays, the equivalent of VectorQ is MatrixQ and ArrayQ. It's worth noting that VectorQ[..., NumericQ] (and its relatives MatrixQ and ArrayQ) are highly optimized and will avoid unpacking packed arrays: ...


14

There is in fact an easy test to determine if an integer is a power of $2$, thanks to bit twiddling: hadamardMatrix[1] := {{1}} hadamardMatrix[2] := {{1, 1}, {1, -1}} hadamardMatrix[n_Integer /; Positive[n] && BitAnd[n, n - 1] == 0] := KroneckerProduct[hadamardMatrix[2], hadamardMatrix[n/2]]


13

As @MikeHoneychurch observes, the formatted form of an SQLConnection expression: SQLConnection["db", 3, "Open", "Catalog" -> "db", "ReadOnly" -> True] differs from its FullForm: SQLConnection[JDBC[...], JLink`Objects`vm1`JavaObject18126325894086657, 1, ...] Pattern matching uses the FullForm. One way to work around this is to convert the ...


12

Preamble This has been discussed before, and this problem was also identified and partially addressed in the same question. I will use a slightly simpler implementation which also covers UpValues. It is probably not complete either, but it covers many common cases of interest. Implementation Here is the code: ClearAll[symbolicHead]; ...


12

duplicatesQ = # != DeleteDuplicates[#] & Usage: duplicatesQ[{1, 4, 6, 1}] (* ===> True *) duplicatesQ@{1, 4, 6, 2} (* ==> False *) duplicatesQ@{{1, 2, 3}, {2, 0, 0}, {1, 2, 3}, {2, 1, 2}} (* ==> True *) duplicatesQ /@ {{1, 2, 3}, {2, 0, 0}, {1, 2, 3}, {2, 1, 2}} (* ==> {False, True, False, True} ) or (to also get the duplicate ...


11

An interesting question which I've never specifically considered before. Some observations: Log[8]/Log[2] // FullSimplify Log2[8] Log[2, 8] 3 3 3 And @@ IntegerQ /@ Log2[2^Range[50000]] And @@ Table[IntegerQ@Log2[2^RandomInteger[5*^8]], {500}] True True Mathematica documentation explicitly states: Log2 gives exact integer or rational ...


11

If I understand the question you are essentially displeased (for your application) that: MemberQ[{x[1, 2], x[3, 4]}, x[1, _]] True What you need is Verbatim: MemberQ[{x[1, 2], x[3, 4]}, Verbatim[ x[1, _] ]] False Select[ {{"foo", "bar"} -> "a", {"foo", "baz"} -> "a", {"foo", _} -> "a"}, MemberQ[{{"foo", "bar"}}, Verbatim @ #[[1]]] ...


11

I think a solution based on pattern matching will be much faster than using Element (which is more mathematical in nature) or only pattern tests or anything else that forces evaluation, since we can bypass the main evaluator. However, it is not possible to completely escape evaluation, because there can be infinitely large number of possibilities for a real ...


11

Maybe upperTriangularMatrixQ2[mat_?MatrixQ] /; Equal @@ Dimensions@mat := UpperTriangularize@mat == mat; test = RandomInteger[{1, 100}, {1000, 1000}]; upperTriangularMatrixQ@test // AbsoluteTiming {2.126050, False} upperTriangularMatrixQ2@test // AbsoluteTiming {0.003277, False} test2 = UpperTriangularize@test; upperTriangularMatrixQ@test2 ...


10

Update Sorry for my ignorance not taking into account that the question specifically asked for a Mathematica 7 solution. I updated the complete post. Mathematica 7 In Mathematica 7 we don't have the option the compile code into a C-library which includes the thread parallelization which can be turned on when using RuntimeAttributes->Listable and ...


10

Using the core of my new step function: SetAttributes[valueQ1, HoldAll] valueQ1[expr_] := Module[{P, R = False}, P = (P = Return[R = True, TraceScan] &) &; TraceScan[P, expr, TraceDepth -> 1]; R ] SetAttributes[valueQ2, HoldAll] valueQ2[expr_] := Module[{P, R = False}, P = (P = Return[R = True, TraceScan] &) &; ...


9

Since you are looking for duplicates you could adapt any of the methods shown in this answer. Using the first one for example: dupeQ = Module[{f}, f[y_] := (f[y] := Return[True, Module]; y); Scan[f, #]; False ] &; This particular one has an advantage on long lists in that it will "short-circuit" on the first duplicate found rather than ...


9

You could also let the pattern matcher do all the work: DuplicatesQ[l_] := MatchQ[l, {___,x_,___,x_,___}] Or: DuplicatesQ[{___,x_,___,x_,___}] := True DuplicatesQ[_] := False


9

RealQ[x_] := Element[x, Reals] === True It fulfills all your samples and I think is generally correct.


9

You did not specify if this test should be optimized for the positive or negative case. If most of your matrices will fail the test it can be greatly beneficial to have an early exit behavior. For example if the lower left element in the matrix is not zero you can fail the matrix after a single element test! And even in the positive case the elements on ...


8

It has been explained in good detail why your inputs did not work the way you wanted them; however, there is still a way to get what you want: Resolve[Exists[n, Element[n, Primes] && Mod[n, 2] == 0]] True FindInstance[Element[n, Primes] && Mod[n, 2] == 0, n, Integers] {{n -> 2}} In general, use Element[n, Primes] whenever you need to ...


7

You could use Gather and then check the length of each group : Gather[{{1, 2, 3}, {2, 0, 0}, {1, 2, 3}, {2, 1, 2}}] (* {{{1, 2, 3}, {1, 2, 3}}, {{2, 0, 0}}, {{2, 1, 2}}} *) Length[#] & /@ Gather[{{1, 2, 3}, {2, 0, 0}, {1, 2, 3}, {2, 1, 2}}] (* {2, 1, 1} *)


7

A frivolous implementation using patterns: duplicateQ[list_]:=MemberQ[Tally[list],{_,_?(#>1&)}] This function uses Tally to arrange the elements of list in bins. For example, In[2]:= Tally[{1,2,3,1,2}] Out[2]= {{1,2},{2,2},{3,1}} Then we look for an element in the output of Tally which looks like {_,n} with $n>1$. In[3]:= ...


7

Needs["DatabaseLink`"] conn = DatabaseLink`OpenSQLConnection[ DatabaseLink`JDBC[ "MySQL(Connector/J)", "localhost:3306/railfreight"], "Username" -> "", "Password" -> ""] (* SQLConnection[1, "Open", "Catalog" -> "railfreight", "TransactionIsolationLevel" -> "RepeatableRead"]*) But when you check out the FullForm (removed ...


6

Neither Resolve or FindInstance hold their arguments, so they evaluate immediately, and we have: In[68]:= Exists[n, EvenQ[n] && PrimeQ[n]] Out[68]= False In[69]:= EvenQ[n] && PrimeQ[n] Out[69]= False So the code isn't really doing what you're expecting it to.


6

FreeQ[] expects an object or a pattern as its second argument, as opposed to a Boolean function. What you should be doing is FreeQ[{2, 1}, _?(# > 1 &)]. Yes, the parentheses are needed. A similar statement applies to the other pattern-matching functions of Mathematica, e.g. Cases[], Position[], and MatchQ[].


6

I don't think there are any built-in functions for this but the following is probably fast enough for most purposes. isSq = Compile[{{n, _Integer}}, With[{test = Sqrt[n]}, Floor[test] == test]]; Does 1 million integers in under a second. Timing[Table[isSq[i], {i, 1, 1000000}]][[1]] (* 0.76195 *) This is under 2 orders of magnitude faster than the ...


6

You can also use MakeExpression ValueQ @@ MakeExpression["abc2"]



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