Advertisement
Guest User

[CentralOH] Python Parsing Puzzle

a guest
Dec 6th, 2014
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.05 KB | None | 0 0
  1. import ast
  2. import math
  3. import re
  4.  
  5.  
  6. def get_coeffs(eqn_str):
  7.     """returns a dict of coefficient: value using the python ast"""
  8.     ret = {}
  9.     # the operations we are interested in are leaves of the parse tree (except
  10.     # the dangling constant)
  11.     for node in ast.walk(ast.parse(eqn_str)):
  12.         if isinstance(node, ast.BinOp):
  13.             if not isinstance(node.left, ast.Num):
  14.                 continue
  15.  
  16.             # the dangling constant does not involve a name for the BinOp, we
  17.             # set the coefficient to 1
  18.             if isinstance(node.right, ast.Name):
  19.                 ret[node.right.id] = node.left.n
  20.             else:
  21.                 ret[1] = node.left.n
  22.     return ret
  23.  
  24.  
  25. def eval_formula(eqn_str, constants_dict):
  26.     """
  27.    evaluates a formula given a constants dict, e.g: {'A': 1, 'B': 2}
  28.    """
  29.     ret = 0
  30.     for name, value in get_coeffs(eqn_str).iteritems():
  31.         # handle dangling constant
  32.         if name == 1:
  33.             ret += value
  34.             continue
  35.  
  36.         # handle the other terms, 0 if unspecified
  37.         ret += constants_dict.get(name, 0) * value
  38.     return math.tanh(ret)
  39.  
  40.  
  41. def read_formulas(filename):
  42.     """reads the formulas and returns a list of formulas"""
  43.     FORMULA_RE = re.compile('^H\d+:$', re.MULTILINE)
  44.     with open(filename) as fp:
  45.         return [m.replace("\n", "") for m in FORMULA_RE.split(fp.read())]
  46.  
  47.  
  48. if __name__ == "__main__":
  49.     formulas = read_formulas("formulas.txt")
  50.     # assume we have some data here!
  51.     CONSTANTS = {}
  52.  
  53.     # first formula is the master formula
  54.     master_formula = get_coeffs(formulas[0])
  55.  
  56.     final = 0
  57.     for idx, formula in enumerate(formulas[1:]):
  58.         # match the equation to the master
  59.         eqn_name = "H%d" % (idx + 1)
  60.         multiplier = master_formula.get(eqn_name, 0)
  61.  
  62.         # compute the term for the relevant formula
  63.         final += multiplier * eval_formula(formula, CONSTANTS)
  64.  
  65.     # lastly, add in value for the dangling constant, 0 if unspecified
  66.     final += master_formula.get(1, 0)
  67.     print final
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement