Created
February 27, 2013 22:37
-
-
Save valtron/5052500 to your computer and use it in GitHub Desktop.
Script to enumerate rational numbers
This file contains 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
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