Sun, 19 Apr 2015 20:04:05 +0300
- added hex support to the calculator
calc.py | file | annotate | diff | comparison | revisions |
--- a/calc.py Sun Apr 19 19:48:32 2015 +0300 +++ b/calc.py Sun Apr 19 20:04:05 2015 +0300 @@ -32,6 +32,7 @@ import random import time import operator +import string from copy import deepcopy epsilon = 1e-10 @@ -203,12 +204,32 @@ Symbols += Tokens Symbols = sorted (Symbols, key=lambda x: len (x), reverse=True) +ContainsHex = False def parse_number (expr): """Tries to parse a number from the expression. Returns (value, length) on success.""" + global ContainsHex i = 0 value = None + # Possibly it's hexadecimal + if expr[0:2].lower() == '0x': + ContainsHex = True + i = 2 + value = '' + + while i < len (expr) and expr[i] in string.hexdigits: + value += expr[i] + i += 1 + + if i < len(expr) and expr[i] == '.': + raise ValueError ('hexadecimal floating point numbers are not supported') + + if not value: + raise ValueError ('not a valid hexadecimal number: %s' % expr[0:i+1]) + + return (complex (int (expr[2:i], 16), 0), i) + if expr[0] == 'i': # Special case, we just have 'i' -- need special handling here because otherwise this would # call float('') in the complex number routine, which throws an error. @@ -242,6 +263,8 @@ return None def tokenize (expr): + global ContainsHex + ContainsHex = False expr = re.sub ('\s+', '', expr.strip()) i=0 tokens = [] @@ -466,6 +489,9 @@ if rep[-1] == '.': rep = rep[:-1] + if '.' not in rep and ContainsHex: + rep = '0x%X' % int (x) + return rep def repr_imaginary (x):