Skip to content

Instantly share code, notes, and snippets.

@rosemichaele
Last active May 7, 2021 20:57
Show Gist options
  • Save rosemichaele/40ad5ee6827c2e4cc6857407a7d72e05 to your computer and use it in GitHub Desktop.
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.
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