Skip to content

Instantly share code, notes, and snippets.

@valtron
Created February 27, 2013 22:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save valtron/5052500 to your computer and use it in GitHub Desktop.
Save valtron/5052500 to your computer and use it in GitHub Desktop.
Script to enumerate rational numbers
from itertools import izip, imap
from fractions import Fraction, gcd
def main():
for x in rationals():
print x
def rationals():
yield Fraction()
for x in combine(imap(const, naturals())):
yield x
yield -x
def naturals():
n = 1
while True:
yield n
n += 1
def combine(streams):
tmp = []
while True:
tmp.append(next(streams))
for stream in tmp:
yield next(stream)
def const(k):
yield Fraction(k, 1)
i = 2
while True:
if gcd(k, i) == 1:
yield Fraction(k, i)
i += 1
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment