def __init__(self, str, precedence = None): self.operator = str if not precedences.has_key(str): raise CalcException("unknown operator %s" % str) if not precedence: precedence = precedences[self.operator] self.precedence = precedence
def getBaseUnit(str): if prefixes.has_key(str): return prefixes[str] elif units.has_key(str): return units[str] else: raise CalcException("unknown unit %s" % str)
def convertToCompatibleUnits(self, other): if self.units == other.units: return other recip = other.reciprocal() if recip and self.units == recip.units: return recip if self.makeBaseUnits() or other.makeBaseUnits(): return self.convertToCompatibleUnits(other) raise CalcException("incompatible units in %s and %s" % (self, other))
def parseToken(self, t): debugPrint("parsing %s" % t) if (t == "in") or (t == "to"): self.parsingConversion = True if len(t) < 1: return False for r in self.regexes: if r.match(t): value = self.regexes[r](t) self.processValue(value) return True raise CalcException("unknown token %s" % t) return False
def pow(self, op, other): if other.units: raise CalcException( "exponent is not allowed to have units in (%s)^%s" % (self, other)) a = self.value b = other.value n = Number(a**b, self.isConversion) for unit in self.units: count = self.units[unit] count *= b if abs(count - round(count)) > 0.000001: n.units = self.units n.value = self.value n.makeBaseUnits() n.value = n.value**other.value if n.units: raise CalcException("exponent/unit mismatch in (%s)^%s" % (self, other)) break n.addUnitCount(unit, int(round(count))) return n
def eval(self, op, other): n = None funcs = { '+': self.addSub, '-': self.addSub, '*': self.divMul, '/': self.divMul, '^': self.pow, 'in': self.convert, 'to': self.convert } if funcs.has_key(op): return funcs[op](op, other) else: raise CalcException("unimplemented operator %s" % op)
def get(str): if units.has_key(str): return units[str] else: raise CalcException("unknown unit %s" % str)
substr = str[:l] if l < len(str) and prefixes.has_key(substr): unit = prefixes[substr] elif units.has_key(substr): unit = units[substr] elif constants.has_key(substr): unit = constants[substr] if unit != None: if l == len(str): return [unit] else: try: return [unit] + parseUnits(str[l:]) except CalcException, inst: pass raise CalcException("unknown unit %s" % str) def getBaseUnit(str): if prefixes.has_key(str): return prefixes[str] elif units.has_key(str): return units[str] else: raise CalcException("unknown unit %s" % str) baseUnits = [ Unit('m', 'meter'), Unit('g', 'gram'), Unit('s', 'second'),