Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import ast
- import math
- import re
- def get_coeffs(eqn_str):
- """returns a dict of coefficient: value using the python ast"""
- ret = {}
- # the operations we are interested in are leaves of the parse tree (except
- # the dangling constant)
- for node in ast.walk(ast.parse(eqn_str)):
- if isinstance(node, ast.BinOp):
- if not isinstance(node.left, ast.Num):
- continue
- # the dangling constant does not involve a name for the BinOp, we
- # set the coefficient to 1
- if isinstance(node.right, ast.Name):
- ret[node.right.id] = node.left.n
- else:
- ret[1] = node.left.n
- return ret
- def eval_formula(eqn_str, constants_dict):
- """
- evaluates a formula given a constants dict, e.g: {'A': 1, 'B': 2}
- """
- ret = 0
- for name, value in get_coeffs(eqn_str).iteritems():
- # handle dangling constant
- if name == 1:
- ret += value
- continue
- # handle the other terms, 0 if unspecified
- ret += constants_dict.get(name, 0) * value
- return math.tanh(ret)
- def read_formulas(filename):
- """reads the formulas and returns a list of formulas"""
- FORMULA_RE = re.compile('^H\d+:$', re.MULTILINE)
- with open(filename) as fp:
- return [m.replace("\n", "") for m in FORMULA_RE.split(fp.read())]
- if __name__ == "__main__":
- formulas = read_formulas("formulas.txt")
- # assume we have some data here!
- CONSTANTS = {}
- # first formula is the master formula
- master_formula = get_coeffs(formulas[0])
- final = 0
- for idx, formula in enumerate(formulas[1:]):
- # match the equation to the master
- eqn_name = "H%d" % (idx + 1)
- multiplier = master_formula.get(eqn_name, 0)
- # compute the term for the relevant formula
- final += multiplier * eval_formula(formula, CONSTANTS)
- # lastly, add in value for the dangling constant, 0 if unspecified
- final += master_formula.get(1, 0)
- print final
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement