← Back to challenges

Recursion: Farey Sequence

PythonHardrecursionarrayslogic

Instructions

The Farey sequence of order n is the set of all fractions with a denominator between 1 and n (reduced to its lowest terms and ordered ascendingly). Given an n, write a function that returns the Farey sequence as a list, with a string representation of each fraction of the form "numerator/denominator".

Examples

farey(1) ➞ ["0/1", "1/1"]

farey(5) ➞ ["0/1", "1/5", "1/4", "1/3", "2/5", "1/2", "3/5", "2/3", "3/4", "4/5", "1/1"]

farey(7) ➞ ["0/1", "1/7", "1/6", "1/5", "1/4", "2/7", "1/3", "2/5", "3/7", "1/2", "4/7", "3/5", "2/3", "5/7", "3/4", "4/5", "5/6", "6/7", "1/1"]

Notes

  • The sequence should always start with "0/1" and end with "1/1".
  • Optional: Try to solve this with the least lines of code. The shortest solution by far is a lambda function with 149 characters in it, excluding spaces and line break.
python3
Loading editor…
to run
Walks through the solution with reasoning and edge cases.