Skip to main content
All Questions

Build a Calculator

Medium

We want to build a simple calculator that can solve arithmetic expressions like 2 + 2 or 4 * 5 - 10 * 2. Write a function calc(expr) that accepts a string as input and returns the answer as a number. It should follow the normal order of operations and support addition, subtraction, multiplication, and division. Don't worry about parentheses or improperly formatted strings.

Examples

calc("1 + 1") # => 2 calc("5 - 1 - 1") # => 3 calc("84 / 1 / 2") # => 42 calc("5/2 - 2*3") # => -3.5

Related courses

Course

Machine Learning Engineer Interview Prep

Land your dream machine learning role at Meta, Google, Amazon, Apple, Microsoft, Nvidia, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates. Explore ML system design, core concepts, coding, behavioral interviews, and more.

Course

Data Engineering Interview Prep

Land your dream data engineering role at Meta, Google, Amazon, Microsoft, Walmart, DoorDash, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates. Practice data modeling, pipeline design, SQL, coding, behavioral interviews, and more.