5
$\begingroup$

I have two lists of integers. From these lists I want to produce a list where each element is a fraction derived from a corresponding pair of elements in the original lists, the smaller integer of the pair should be in the numerator.

For example, from T1 = {0, 2, 8}, T2 = {3, 5, 6} and I want to produce T ={0, 2/5, 6/8}. But I have no idea how to do it in Mathematica. I will be grateful for any help.

$\endgroup$

4 Answers 4

6
$\begingroup$

One way:

t1 = {0, 2, 8};
t2 = {3, 5, 6};
MapThread[
 If[# > #2, #2/#, #/#2] &,
 {t1, t2}
 ]
$\endgroup$
5
$\begingroup$

A simple numeric approach that is naturally vectorized due to use of Listable functions:

f[a_, b_] := Quiet[ (a/b)^Sign[b - a] ]

Test:

f[ {2, 3, 6, 5, 9, 7, 5}, {5, 4, 3, 4, 9, 3, 1} ]
{2/5, 3/4, 1/2, 4/5, 1, 3/7, 1/5}

Here is a completely different approach based solely on Attributes:

SetAttributes[f2, {Orderless, Listable}]

f2[a_, b_] := a/b

Test:

f2[{3, 1, 7}, {2, 4, 0}]
{2/3, 1/4, 0}
$\endgroup$
4
  • 1
    $\begingroup$ Very nice, but produces an infinite expression error when 0 is in the blist. $\endgroup$
    – SquareOne
    Mar 12, 2015 at 8:59
  • $\begingroup$ @SquareOne I forgot about that case. Thanks. $\endgroup$
    – Mr.Wizard
    Mar 12, 2015 at 9:02
  • 1
    $\begingroup$ This new version is very elegant. By the way, your first version produces a correct answer (it does not fail as you said), the infinite expression message was only a warning not an error as I said (same warning also in one of @Karsten solutions). $\endgroup$
    – SquareOne
    Mar 12, 2015 at 9:16
  • 1
    $\begingroup$ @SquareOne Thanks, again. I guess I could just wrap that in Quiet. $\endgroup$
    – Mr.Wizard
    Mar 12, 2015 at 9:20
3
$\begingroup$
Rational @@@ Sort /@ Transpose[{T1, T2}]
(*{0, 2/5, 3/4}*)
$\endgroup$
2
$\begingroup$
Min@#/Max@# & /@ Transpose[{t1, t2}]
{0, 2/5, 3/4}
Inner[Min@{##}/Max@{##} &, t1, t2, List]
{0, 2/5, 3/4}
t2/t1 /. x : (# > 1 & | ComplexInfinity) -> 1/x
{0, 2/5, 3/4}
$\endgroup$

Your Answer

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

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