Here's the Python code to solve the problem:

function to insert parentheses in lottery questions

def insert_parentheses(expression): # split the expression into a list of operands and operators tokens = expression.split()

# initialize a stack to keep track of the operands
stack = []

# iterate over the tokens from right to left
for i in range(len(tokens)-1, -1, -1):
    token = tokens[i]
    if token.isdigit():
        # if the token is an operand, push it onto the stack
        stack.append(token)
    elif token == 'X':
        # if the token is a multiplication operator, insert parentheses
        # around the next two operands and push the result onto the stack
        op1 = stack.pop()
        op2 = stack.pop()
        subexpr = '(' + op1 + ' X ' + op2 + ')'
        stack.append(subexpr)
    else:
        # if the token is an addition or subtraction operator, push it onto
        # the stack and continue to the next token
        stack.append(token)

# reverse the stack to get the operands in the correct order
operands = list(reversed(stack))

# initialize a new stack to keep track of the subexpressions
stack = []

# iterate over the operands from left to right
for i in range(len(operands)):
    operand = operands[i]
    if operand.isdigit():
        # if the operand is a number, push it onto the stack
        stack.append(operand)
    else:
        # if the operand is a subexpression, insert parentheses around it
        # and push the result onto the stack
        subexpr = '(' + operand + ')'
        stack.append(subexpr)

# join the stack to get the final expression with parentheses inserted
result = ' '.join(stack)

return result

read input

n = int(input()) expressions = [] for i in range(n): expressions.append(input())

process the expressions and print the results

for expression in expressions: result = insert_parentheses(expression) print(result) print() # print a blank line between the results


原文地址: https://www.cveoy.top/t/topic/p0b 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录