From 082389007387c3012d1fb1d6396962d46484a359 Mon Sep 17 00:00:00 2001 From: Lubos Kolouch Date: Thu, 7 Apr 2022 18:33:30 +0200 Subject: feat(challenge-159/lubos-kolouch/p[erl,ython]/ch-[1,2].p[ly]): Challenge 159 Task 1 2 LK Perl Python --- challenge-159/lubos-kolouch/python/ch-1.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 challenge-159/lubos-kolouch/python/ch-1.py (limited to 'challenge-159/lubos-kolouch/python/ch-1.py') diff --git a/challenge-159/lubos-kolouch/python/ch-1.py b/challenge-159/lubos-kolouch/python/ch-1.py new file mode 100644 index 0000000000..cdfcf94d85 --- /dev/null +++ b/challenge-159/lubos-kolouch/python/ch-1.py @@ -0,0 +1,20 @@ +""" Challenge 159 Task 1""" + + +def farey_sequence(n: int, descending: bool = False) -> str: + """Print the n'th Farey sequence. Allow for either ascending or descending.""" + (a, b, c, d) = (0, 1, 1, n) + + solution = [] + if descending: + (a, c) = (1, n - 1) + solution.append(f"{a}/{b}") + while (c <= n and not descending) or (a > 0 and descending): + k = (n + b) // d + (a, b, c, d) = (c, d, k * c - a, k * d - b) + solution.append(f"{a}/{b}") + + return ", ".join(solution) + + +assert farey_sequence(5) == "0/1, 1/5, 1/4, 1/3, 2/5, 1/2, 3/5, 2/3, 3/4, 4/5, 1/1" -- cgit