Advertisement
ChrisProsser

Math_Solver.py

Feb 6th, 2014
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.64 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. # globals
  4. verbose = False # set to True if you want debug info printed
  5. max_iter = 1000 # this stops infinate loops incase the code does not allow for some input
  6.  
  7. def solve(problem_str):
  8.     """
  9.    This task was to create a program that can process simple maths equations
  10.    without the use of any external libraries, lambdas, eval() etc. See Stack
  11.    Overflow question here for more details:
  12.    http://stackoverflow.com/questions/21573436/solving-math-in-python-without-any-built-in-eval-functions-or-external-libraries/21580431#21580431
  13.    """
  14.    
  15.     def multiply(arg_list):
  16.         x = 1
  17.         for i in arg_list:
  18.             x *= i
  19.         return x
  20.  
  21.     def find_innermost(x_str):
  22.         a, b, c = [-1], [0], 0
  23.         while True:
  24.             start = a[-1]+1 # get position just after last opening bracket as start
  25.             a.append(x_str.find('(', start)) # find next (
  26.             b.append(x_str.find(',', start)) # find next ,
  27.             c = x_str.find(')', start)       # find next )
  28.             # if closing bracket is first or no more opening brackets left
  29.             if (a[-1] > c) or (a[-1] == -1):
  30.                  # add to this to allow for more than 2 args by getting last comma before )?
  31.                 if (b[-2] > a[-3]) and (b[-2] < a[-2]):
  32.                     # if there is a comma between opening brackets 2 & 3 steps ago
  33.                     return x_str[b[-2]+1:c+1]
  34.                 else:
  35.                     return x_str[a[-3]+1:c+1]
  36.             if len(a) > max_iter:
  37.                 raise Exception("Stuck in find_innermost loop")
  38.  
  39.     def do_sum(x_str):
  40.         # get function arguements as integers from command string
  41.         args = [int(x) for x in x_str[x_str.find('(')+1:x_str.find(')')].split(',')]
  42.         task = x_str[:3].lower() # get function to be performed from command string
  43.         if task == 'add':
  44.             return sum(args)
  45.         elif task == 'sub':
  46.             return args[0] - sum(args[1:])
  47.         elif task == 'abs':
  48.             if len(args) > 1:
  49.                 raise Exception("Only one arguement can be supplied for abs() function")
  50.             return abs(args.pop())
  51.         elif task == 'mul':
  52.             return multiply(args)
  53.         else:
  54.             print x_str + ': Task not recognised, please modify program or input'
  55.             raise Exception("Invalid input")
  56.    
  57.     # solve function starts here...
  58.     i = 0
  59.     while True:
  60.         i += 1
  61.         if verbose: print 'debug: problem_str:', problem_str
  62.         # find innermost nested problem if >1 opening bracket...
  63.         if problem_str.count('(') > 1:
  64.             x_str = find_innermost(problem_str)
  65.         else:
  66.             x_str = problem_str
  67.         if verbose: print '.'*6, 'x_str:\t', x_str
  68.         # process individual problem extracted from string...
  69.         x = do_sum(x_str)
  70.         if verbose: print '.'*6, 'x:\t', x, '\n'
  71.         # replace individual problem with solution in full problem string...
  72.         problem_str = problem_str.replace(x_str, str(x))
  73.         # return result if no problems remaining in string...
  74.         if problem_str.count('(') == 0:
  75.             return int(problem_str)
  76.         if i >= max_iter:
  77.             raise Exception("Stuck in main loop")
  78.        
  79.  
  80. # test solve function...
  81. p1 = 'abs(add(add(9465,38),multiply(add(63303,146),46)))'
  82. p2 = 'abs(add(multiply(95,multiply(-1,multiply(13,18875))),multiply(-1,add(18293,26))))'
  83. p3 = 'abs(add(subtract(add(add(151,26875),122),254),subtract(237,multiply(-1,56497))))'
  84. r1, r2, r3 = solve(p1), solve(p2), solve(p3)
  85. print 'p1 evaluates to:', r1
  86. print 'p2 evaluates to:', r2
  87. print 'p3 evaluates to:', r3
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement