Trains the technique from
LeetCode 736Parse Lisp ExpressionThis is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.
Same function shape, different story and different numbers.
A plant writes the quantities on its batch sheets in a tiny macro language, and the loader has to reduce each sheet to a single whole number.
A term is one of the following, and nothing else.
- followed by one or more digits, such as 12 or -40. Its value is that integer.v or x2 or feedrate. The three words plus, times and with are reserved and are never used as labels. A label's value is the value currently in force for it.(plus A B), whose value is the value of term A added to the value of term B.(times A B), whose value is the value of term A multiplied by the value of term B.(with L1 A1 L2 A2 ... Ln An B), which puts labels into force. After with come one or more pairs, each a label followed by the term giving its value, and then one final term B. The value of the whole with is the value of B.The rules for a with are these.
A1 is reduced before L1 is in force, term A2 is reduced with L1 already in force, term A3 with L1 and L2 in force, and so on. Term B is reduced with all n labels in force.with. The later pair takes over from the point it appears onward.with hides whatever value that label carried outside the with, and only until that with is finished. Once the with is done, the hidden outer value is back in force.program holds one term. Tokens are separated by single spaces, there is no space just inside a bracket, and there is no leading or trailing space. Every label used as a term has a value in force at the point it is used. Parse the text yourself; do not hand it to a language evaluator such as eval.
Return the value of program.
Example 1
The inner `with` puts `base` at 9 only inside itself, so its body `(times base 2)` is 18 and `span` becomes 18. The inner `with` is then finished, so `base` is back at 5 and the body `(plus base span)` is 5 + 18.
Example 2
The pair for `b` is reduced with `a` already at 3, so `b` becomes 3 + 4 = 7, and the body `(times a b)` is 3 * 7.
Example 3
`x2` is a legal label: it starts with a letter and then carries a digit. It is put at 7, so the body `(plus x2 x2)` is 7 + 7.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def evaluate_recipe(program: str) -> int:public int evaluateRecipe(String program)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.