Skip to content

Proposed fix to Ternary-Expression on TIP 102-Unit-7 wiki #23

@Enochteo

Description

@Enochteo

Hi CodePath team,

While working through TIP102 Unit 7, I found that the Ternary Expression solution does not handle Boolean values like 'T' or 'F' correctly when they appear as leaf values instead of conditions like the example on the portal print(evaluate_ternary_expression_recursive("T?T?F:5:3"))

I've made a fix that ensures the base case properly distinguishes between 'T'/'F' values and ternary condition expressions, I don't know if you mind.

Here is the updated version of the recursive function:

def evaluate_ternary_expression_recursive(expression):
    def helper(i):
        # Base case: return a digit or boolean value if it's just that
        if i >= len(expression) or expression[i] not in 'TF?' or (expression[i] in 'TF' and (i+1 >= len(expression) or expression[i+1] != '?')):
            return expression[i], i

        # Current character should be a condition (either 'T' or 'F')
        condition = expression[i]
        i += 2  # Skip condition and '?'

        # Recursively evaluate the true_expression
        true_val, i = helper(i)

        i += 1  # Skip ':'
        # Recursively evaluate the false_expression
        false_val, i = helper(i)

        if condition == 'T':
            return true_result, i
        else:
            return false_result, i

    result, _ = helper(0)
    return result

Sorry if I'm being a nuisance.

Thank you.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions