Computing Expressions

So, right now I'm applying for various internships. And one of them reached out to me with an assessment link. The link had 90 mins and gave me 2 questions to solve.

I'll be sharing those questions and my answers here. I'll make it a 2 part series, because (I'll be honest) I couldn't solve the second question. So, I guess I have another week to figure it out, and the solution to the next question would be my next blog. 

Anyways, without further ado, here's the first question :

Write a program that takes a single line of input, representing an arithmetic expression. The expression will consists of numeric digits (0-9), the plus operator (+) and the multiplication operator (*). The given expression will be a valid arithmetic expression (i.e., "*2++" is not valid).

Your task is to evaluate the arithmetic expression, following the normal rules of operator precedence, and print the result without any leading or trailing whitespace.

The resulting number will fit in a normal integer.

Note: Solutions such as "eval()" in python are elegant, but not what we are looking for here. Please evaluate the expressions with your own code :) 

Example Input 

20+2*3

Example Output

26

Here's what I was thinking : 

Since our input would be a string, our first task should be to take that string and convert it into an actual expression that we can evaluate. 



So, this is what I came up with:

def get_expr(expression):
    expr = []
    num = 0
    for i in expression:
        if (i != "+") and (i != "*"):
            num = (num * 10) + int(i)
        elif (i == "+") or (i == "*"):
            expr.append(num)
            expr.append(i)
            num = 0

    expr.append(num)

    return expr




Comments

Popular posts from this blog

Solving Sudoku

Plotly