Created
January 30, 2012 23:51
-
-
Save jcorbin/1707618 to your computer and use it in GitHub Desktop.
Division Demo
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
#!/usr/bin/python | |
# Example usage: | |
# $ ./division_deom.py 1 7 | |
# 0 1 | |
# . | |
# 1 3 | |
# 4 2 | |
# 2 6 | |
# 8 4 | |
# 5 5 | |
# 7 1 | |
# | |
# $ ./division_demo.py 1 9801 --chunk 2 | |
# 0 1 | |
# . | |
# 00 10 100 | |
# 01 1000 199 | |
# 02 1990 298 | |
# 03 2980 397 | |
# ... | |
# 96 6841 9604 | |
# 97 7831 9703 | |
# 99 8821 1 | |
import argparse | |
parser = argparse.ArgumentParser() | |
parser.add_argument('numer', type=int) | |
parser.add_argument('denom', type=int) | |
parser.add_argument('-c', '--chunk', type=int, default=1) | |
args = parser.parse_args() | |
def divison_residues(n, d, base=10): | |
while True: | |
q, r = divmod(n, d) | |
yield q, r | |
n = r * base | |
def until_repeated_residue(digit_residues): | |
first = None | |
for digit, residue in digit_residues: | |
if first is None: | |
if residue != 0: | |
first = residue | |
elif residue == first: | |
break | |
yield digit, residue | |
from itertools import islice | |
def chunk(n, iterable): | |
while True: | |
c = tuple(islice(iterable, n)) | |
if not c: | |
break | |
yield c | |
digit_residues = divison_residues(args.numer, args.denom) | |
unit, residue = next(digit_residues) | |
print(unit, residue) | |
print('.') | |
digit_residues = until_repeated_residue(digit_residues) | |
if args.chunk == 1: | |
for digit, residue in digit_residues: | |
print(digit, residue) | |
else: | |
for drs in chunk(args.chunk, digit_residues): | |
digits, residues = zip(*drs) | |
print(''.join(map(str, digits)), *residues) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment