Last active
May 7, 2021 20:57
-
-
Save rosemichaele/40ad5ee6827c2e4cc6857407a7d72e05 to your computer and use it in GitHub Desktop.
Use a generator function for the Calkin-Wilf sequence to determine where in the sequence a given rational number lies.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def calkin_wilf_sequence(number): | |
def fractions(): | |
from fractions import Fraction | |
i = Fraction(1/1) | |
while True: | |
yield [i.numerator, i.denominator] | |
i = Fraction(1 / (2*int(i) - i + 1)) | |
gen = fractions() | |
res = 0 | |
while next(gen) != number: | |
res += 1 | |
return res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment