# Python Example – Write a Python program to parse math formulas and put parentheses around multiplication and division # (Python Example for Beginners)

Write a Python program to parse math formulas and put parentheses around multiplication and division.

Sample Solution:

Python Code:

``````
import ast

def recurse(node):
if isinstance(node, ast.BinOp):
if isinstance(node.op, ast.Mult) or isinstance(node.op, ast.Div):
print('(', end='')
recurse(node.left)
recurse(node.op)
recurse(node.right)
if isinstance(node.op, ast.Mult) or isinstance(node.op, ast.Div):
print(')', end='')
print('+', end='')
elif isinstance(node, ast.Sub):
print('-', end='')
elif isinstance(node, ast.Mult):
print('*', end='')
elif isinstance(node, ast.Div):
print('/', end='')
elif isinstance(node, ast.Num):
print(node.n, end='')
else:
for child in ast.iter_child_nodes(node):
recurse(child)

def search_expr(node):
returns = []
for child in ast.iter_child_nodes(node):
if isinstance(child, ast.Expr):
return child
returns.append(search_expr(child))
for ret in returns:
if isinstance(ret, ast.Expr):
return ret
return None

formula = '4+5*7/2'

a = ast.parse(formula)

expr = search_expr(a)
if expr is not None:
recurse(expr)
print()
``````

Sample Output:

`4+((5*7)/2)`

# Special 95% discount

## 2000+ Applied Machine Learning & Data Science Recipes

### Portfolio Projects for Aspiring Data Scientists: Tabular Text & Image Data Analytics as well as Time Series Forecasting in Python & R ## Two Machine Learning Fields

There are two sides to machine learning:

• Practical Machine Learning:This is about querying databases, cleaning data, writing scripts to transform data and gluing algorithm and libraries together and writing custom code to squeeze reliable answers from data to satisfy difficult and ill defined questions. It’s the mess of reality.
• Theoretical Machine Learning: This is about math and abstraction and idealized scenarios and limits and beauty and informing what is possible. It is a whole lot neater and cleaner and removed from the mess of reality.
`Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.  `