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

763. Evaluate an expression with plus and times, no parentheses

EasyTokenization and NLP

Calculators, config languages and even reward checkers for math answers need a small parser. Start with the simplest grammar that still has operator precedence.

Write evaluate(expr) for a string of non-negative integers joined by '+' and '*', with any number of spaces. Multiplication binds tighter than addition. Return the integer result.

Functiondef evaluate(expr)

Example 1

Input: evaluate('2 + 3 * 4')

Output: 14

Example 2

Input: expr = ' 42 '

Output: 42

Example 3

Input: expr = '2*3*4+1'

Output: 25

Constraints

  • Input is always valid.
  • No parentheses or minus signs.
Hint 1

Strip all spaces first.

Hint 2

Split on the lower precedence operator.

Hint 3

Start each product at 1 and the sum at 0.

Common mistakes
  • Evaluating left to right and getting 20 for '2 + 3 * 4'.
  • Starting the product at 0.
Understand the idea

Operator precedence means some operators group first. With only + and *, the expression is a sum of products: 2 + 3 * 4 is 2 + (3 * 4) = 14, not (2 + 3) * 4 = 20. So you can split on the weaker operator, evaluate each piece with the stronger operator, and combine. This split by precedence level is the seed of recursive descent parsing, where each precedence level becomes one function. The same idea shows up when you tokenize and check model answers to arithmetic questions.

Topics
Tokenization and NLP
Similar questions
  • Score words by TF-IDFEasy
  • Encode text with a byte fallback so no character is ever unknownEasy
  • Normalize text by lowercasing, stripping accents and collapsing spacesEasy
  • Count word n-grams and return the k most frequent with stable tiesEasy
All Tokenization and NLP problems
Report
763 / 903
Python 3solution.pyPython idle
1
2
3
4
def evaluate(expr):
# return the integer value
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 6 tests.

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