BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Tokenization and NLP32 of 38 in topic

764. Evaluate an arithmetic expression with precedence, parentheses and unary minus

MediumTokenization and NLP Pro

Checking a math answer, a calculator tool for an agent, or a tiny config language all need an expression evaluator that respects operator precedence. Using eval is not allowed.

Write evaluate_expression(expr). expr contains non-negative integers, '+', '-', '*', '/', parentheses and spaces. '*' and '/' bind tighter than '+' and '-', and operators of the same precedence go left to right. '/' is integer division that truncates toward zero. A '-' at the start or right after '(' is a unary minus. The input is always valid and never divides by zero.

Functiondef evaluate_expression(expr)

Example 1

Input: evaluate_expression('3+2*2')

Output: 7

Example 2

Input: evaluate_expression('(1+(4+5+2)-3)+(6+8)')

Output: 23, and evaluate_expression('-7/2') returns -3

Constraints

  • Length up to 10,000 characters.
  • Nesting depth up to 200.
  • Integers can be large; Python ints do not overflow.
Hint 1

Strip spaces first.

Hint 2

Write the grammar before the code.

Hint 3

Python's // floors; the task wants truncation toward zero.

Common mistakes
  • Evaluating strictly left to right and ignoring precedence.
  • Making '-' right associative by recursing on the right side.
  • Using // directly and getting -4 for -7/2.
  • Forgetting unary minus after '('.
Understand the idea

Operator precedence maps neatly to a recursive descent parser: each precedence level is a function that calls the next tighter level for its operands. Parentheses and unary minus live at the tightest level, factor. A stack-based approach (shunting yard, or a running sum with a last term for + - * /) is the common alternative and is worth knowing as a follow-up.

Topics
Tokenization and NLP
Similar questions
  • Do one merge step of a BPE tokenizerMedium
  • Compute Levenshtein edit distanceMedium
  • Tokenize words with WordPiece greedy longest matchMedium
  • Build a vocabulary with special tokens, a minimum frequency and UNKMedium
All Tokenization and NLP problems
Report
764 / 903
Python 3solution.pyPython idle
1
2
3
4
def evaluate_expression(expr):
# no eval(); return an int
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS