# HG changeset patch # User Jeff Hammel # Date 1425444957 28800 # Node ID 570ceafeb67099fd002c2368084d6c983b7270f5 # Parent f6d885adb3d7708e07d12b8e0e14c5f933a2539b STUB: numerics/text_display.py diff -r f6d885adb3d7 -r 570ceafeb670 numerics/text_display.py --- a/numerics/text_display.py Tue Mar 03 20:23:34 2015 -0800 +++ b/numerics/text_display.py Tue Mar 03 20:55:57 2015 -0800 @@ -7,21 +7,24 @@ # imports import argparse +import sys +from collections import OrderedDict +from math import floor # module globals -__all__ = ['main', 'frac', 'FracParser'] +__all__ = ['main', 'blocks', 'frac', 'FracParser'] # Unicode is awesome; see http://www.alanwood.net/unicode/block_elements.html -blocks = {0.: '', - 0.125: '▏', - 0.25: None, # TODO, - 0.375: None, - 0.5: None, - 0.625: None, - 0.75: None, - 0.875: None, - 1.: '█' - } +blocks = OrderedDict([(0., ''), + (0.125, '▏'), + (0.25, '▎'), + (0.375, '▍'), + (0.5, '▌'), + (0.625, '▋'), + (0.75, '▊'), + (0.875, '▉'), + (1., '█'), + ]) def iterable(obj): @@ -34,14 +37,25 @@ return False -def frac(fractions, width=20, bar='│'): +def frac(fractions, width=20, bar=''): """display fractions""" if not iterable(fractions): # convert single item to list fractions = [fractions] retval = [] for fraction in fractions: - raise NotImplementedError('TODO') # -> record TODO items + whole = int(floor(fraction*width)) + part = (fraction*width)-whole + line = blocks[1.]*whole + blocks[int(floor(part * 8))/8.] + retval.append(line) + if bar: + lines = [] + for line in retval: + newline = "{bar}{}{bar}".format(line.ljust(width), + bar=bar) + lines.append(newline) + retval = lines + return retval class FracParser(argparse.ArgumentParser): @@ -50,10 +64,10 @@ kwargs.setdefault('formatter_class', argparse.RawTextHelpFormatter) kwargs.setdefault('description', __doc__) argparse.ArgumentParser.__init__(self, **kwargs) - self.add_argument('fraction', type=float, nargs='+' + self.add_argument('fraction', type=float, nargs='+', help="fractions to display") self.add_argument('-w', '--width', dest='width', - type=int, default=20, + type=int, default=40, help="width to display [DEFAULT: %(default)s]") self.options = None @@ -68,7 +82,7 @@ if options.width < 1: self.error("Width must be greater than zero (You gave: {})".format(options.width)) out_of_range = [i for i in options.fraction - if not (0. < i < 1.)] + if not (0. <= i <= 1.)] if out_of_range: self.error("Fractions should be between 0 and 1") @@ -79,6 +93,11 @@ parser = FracParser() options = parser.parse_args(args) + # get fractions display + lines = frac(options.fraction, width=options.width) + + # display + print ('\n'.join(lines)) if __name__ == '__main__': main()