4
$\begingroup$

I would like to know how to sort a set of fractions with respect to numerator (or denominator) or both. For example sort $$ 3/5, 13/21, 19/30, 2/3, 5/7, 11/15, 3/4, 11/14, 4/5, 5/6, 7/8, 9/10, 1 $$ with respect o numerator to get $$ 1,2/3,3/5,3/4,4/5,5/7,5/6,7/8,9/10,11/15, 11/14,13/21, 19/30 $$ or with respect to both (first numerator, then denominator) $$ 1,2/3,3/4,3/5,4/5,5/6,5/7,7/8,9/10,11/14,11/15,13/21,19/30 $$

Thanks!

$\endgroup$
1
8
$\begingroup$

From SortBy >> Details:

Mathematica graphics

So, for the second requirement, you can simply do

SortBy[lst, {Numerator, Denominator}]

Mathematica graphics

$\endgroup$
2
  • $\begingroup$ Thanks for pointing this out, I didn't know you could give SortBy a list of functions. $\endgroup$ – Kiro Jan 11 '17 at 10:20
  • 1
    $\begingroup$ @Kiro, it is hidden in the "Details" section. $\endgroup$ – kglr Jan 11 '17 at 10:37
6
$\begingroup$

Here is one way, more or less similar to what others have already suggested.

list = {3/5, 13/21, 19/30, 2/3, 5/7, 11/15, 3/4, 11/14, 4/5, 5/6, 7/8,
9/10, 1};

SortBy[list, Numerator]
(*{1, 2/3, 3/5, 3/4, 4/5, 5/7, 5/6, 7/8, 9/10, 11/15, 11/14, 13/21, \
19/30}*)

SortBy[list, Denominator]
(*{1, 2/3, 3/4, 3/5, 4/5, 5/6, 5/7, 7/8, 9/10, 11/14, 11/15, 13/21, \
19/30}*)

EDIT: In the case where the list should first be sorted by numerator, and then such that successive runs of identical numerators are sorted by denominator, one could do this by using SplitBy, Map and Flatten. This is probably not the only way to go about it, but anyway:

listnumsort = SortBy[list, Numerator];

listnumsortsplit = SplitBy[listnumsort, Numerator];

listfullsortsplit = Map[SortBy[#, Denominator] &, listnumsortsplit];

listfullsort = Flatten[listfullsortsplit]
(*{1, 2/3, 3/4, 3/5, 4/5, 5/6, 5/7, 7/8, 9/10, 11/14, 11/15, 13/21, \
19/30}*)

Above, the list is first sorted by numerator, and then split into sublists of successive runs of identical numerators. Each of these sublists is sorted by denominator, and the result is glued back together.

$\endgroup$
2
  • $\begingroup$ Thanks, In the second question I meant first sort by Numerator, then by Denominator, not only by Denominator. $\endgroup$ – asad Jan 11 '17 at 9:58
  • $\begingroup$ I see, I will edit the answer. $\endgroup$ – Kiro Jan 11 '17 at 10:02

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