6
$\begingroup$

I have a list of equations and I solve them

list = {x^2 - 2 x - 3 == 0, 2 x^2 + 3 x + 1 == 0, x^2 - 2 == 0, 
   6 x^2 - 5 x + 1 == 0};
mytab = Table[Solve[list[[i]]], {i, 1, Length[list]}]

{{{x -> -1}, {x -> 3}}, {{x -> -1}, {x -> -(1/2)}}, {{x -> -Sqrt[2]}, {x -> Sqrt[ 2]}}, {{x -> 1/3}, {x -> 1/2}}}

I would like to select the element {{x -> 1/3}, {x -> 1/2}}, because 1/3, 1/2 are rational numbers and not integer numbers. How can I select them?

$\endgroup$
0

6 Answers 6

9
$\begingroup$

One possibility out of many

list={x^2 - 2  x - 3 == 0, 2  x^2 + 3  x + 1 == 0, x^2 - 2==0, 6 x^2 - 5  x + 1== 0};   
Cases[Solve /@ list, {{x -> _Rational}, {x -> _Rational}}]

Mathematica graphics

Note: You do not need to type

mytab = Table[Solve[list[[i]]], {i, 1, Length[list]}]

You can just type Solve /@ list instead.

$\endgroup$
7
$\begingroup$
Cases[{{_ -> _Rational} ..}] @ mytab
{{{x -> 1/3}, {x -> 1/2}}}
Select[FreeQ[_Integer]] @ mytab
{{{x -> 1/3}, {x -> 1/2}}}
$\endgroup$
5
$\begingroup$
Select[mytab, AllTrue[MatchQ[_Rational]]@*Values@*Flatten]
$\endgroup$
5
$\begingroup$
l = {x^2 - 2 x - 3 == 0, 2 x^2 + 3 x + 1 == 0, x^2 - 2 == 0, 6 x^2 - 5 x + 1 == 0};

Using Map instead of Table:

Last@(Solve[# && NotElement[x, Integers], x, Rationals] & /@ l)

(*{{x -> 1/3}, {x -> 1/2}}*)
$\endgroup$
4
$\begingroup$
Pick[mytab,mytab[[All,All,1,2]]/.{{_Rational,_Rational}->True,
  {_,_}->False}]//Catenate

(* {{x->1/3},{x->1/2}} *)

(To be pedantic, the OP is asking that both values have the Head 'Rational')

{Element[#,Rationals],Element[#,Rationals]}&/@mytab[[All,All,1,2]]

(* {{True,True},{True,True},{False,False},{True,True}}  *)
$\endgroup$
3
$\begingroup$
list = {
 {{x -> -1}, {x -> 3}}, 
 {{x -> -1}, {x -> -(1/2)}},
 {{x -> -Sqrt[2]}, {x -> Sqrt[ 2]}}, 
 {{x -> 1/3}, {x -> 1/2}}}

A variant of kglr's first answer using SequenceCases

First /@ SequenceCases[list, {{{_ -> _Rational} ..}}]

{{{x -> 1/3}, {x -> 1/2}}}

Using SequencePosition

p = First /@ SequencePosition[list, {{{_ -> _Rational} ..}}]

{4}

Extract[list, p]

{{x -> 1/3}, {x -> 1/2}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.