Skip to content

Instantly share code, notes, and snippets.

@jtauber
Created August 13, 2009 05:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jtauber/167008 to your computer and use it in GitHub Desktop.
Save jtauber/167008 to your computer and use it in GitHub Desktop.
# Python implementation of the Gibbons-Lester-Bird algorithm[1] for enumerating
# the positive rationals.
#
# James Tauber 2004-07-01
# http://jtauber.com/
#
# [1] http://web.comlab.ox.ac.uk/oucl/work/jeremy.gibbons/publications/rationals.pdf
def rationals():
"""
generates the positive rationals with no duplicates.
"""
r = (0,1)
while True:
r = (r[1], (r[1] * (r[0] // r[1])) + (r[1] - (r[0] % r[1])))
yield r
# ANNOTATED VERSION
#
# def proper_fraction((n, d)):
# return (n // d, (n % d, d))
#
# def reciprocal((n, d)):
# return (d, n)
#
# def one_take((n, d)):
# return (d - n, d)
#
# def improper_fraction(i, (n, d)):
# return ((d * i) + n, d)
#
# def rationals():
# r = (0,1)
# while True:
# n, y = proper_fraction(r)
# z = improper_fraction(n, one_take(y))
# r = reciprocal(z)
# yield r
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment