Mercurial > hg > numerics
changeset 99:570ceafeb670
STUB: numerics/text_display.py
author | Jeff Hammel <k0scist@gmail.com> |
---|---|
date | Tue, 03 Mar 2015 20:55:57 -0800 |
parents | f6d885adb3d7 |
children | e1fec09da207 |
files | numerics/text_display.py |
diffstat | 1 files changed, 35 insertions(+), 16 deletions(-) [+] |
line wrap: on
line diff
--- 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()