Ctrl K

Evaluating Nested Conditions

Medium
You get a string expr built from nested conditional expressions of the form condition?yes:no. The condition is T (true) or F (false); if it is true the expression takes the value of the yes branch, otherwise of the no branch. Each branch is a single digit, a T or F, or another conditional expression. Conditionals group from right to left, as in most programming languages: F?1:T?2:3 means F?1:(T?2:3), and T?F?1:2:3 means T?(F?1:2):3. Evaluate the expression and return its value (a digit, T or F) as a one-character string.
Example 1
expr="F?7:4" → '4'

The condition is false, so we take the branch after :, which is 4.

Example 2
expr="T?F?1:6:9" → '6'

This reads as T ? (F ? 1 : 6) : 9. The outer condition is true, the inner one false, so the result is 6.

Example 3
expr="F?2:F?3:T" → 'T'

This reads as F ? 2 : (F ? 3 : T), so the result is T.

Constraints
  • 5 ≤ len(expr) ≤ 10⁴
  • expr consists of digits and the characters T, F, ?, :
  • expr is a well-formed expression, and every number in it has one digit
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsExpand Repeat Brackets MediumPlus-Minus Calculator With Brackets HardA Calculator With Brackets and Variables HardSimplify a Letter Polynomial HardCalculator With Brackets and Four Operations Hard
loading Python…
Input
expr="F?7:4"
Expected
'4'

Run checks the first 3 tests in your browser. Submit checks all 22 tests on the server, hidden ones included.