How to write a simple math interpreter in Python

Not long ago, I had to write a certain feature for my project. It involved parsing a mathematical expression from plaintext and evaluating it. This feature had to work with basic numerical expressions like 2 + 3, support context to use variables: apples + 2 * oranges, and parentheses: (2 + 3) - apples.

The obvious (and least appropriate) solution was to use eval. This standard function takes a string and runs it, treating it like Python code. This is considered to be very unsafe: eval an execute arbitrary code, which makes it a potential security risk, especially if the input comes from untrusted sources. Malicious users could inject harmful code that could lead to unintended consequences, such as executing system commands or accessing sensitive information.

In this article, I will walk you through my safe and extensible implementation using Python’s ast module.

read more “How to write a simple math interpreter in Python”

do you need math as a programmer?

As more and more positions open for computer programmers and scientists, many are confused: do you need to know math as a software developer? This is a very old question that resulted in countless debates, but common sense and popular opinion still incline that you, indeed, need math in order to succeed. Of course, there are exceptions to any rule and I will try to explain everything I know on this topic in this post.

read more “do you need math as a programmer?”