【问题标题】:Expression trees parsing and execution of operations表达式树解析和操作执行
【发布时间】:2016-11-01 02:32:41
【问题描述】:

我在编码挑战中遇到了这个问题。我无法按时解决它,但我仍然想知道如何解决它。我对表达式树不是很熟悉,我发现很难对问题进行建模。描述是这样的:

输入: expression_tree | sequence_of_operations

输入是单行文本,其中包含表达式树和由| 字符分隔并以\n 换行符结束的操作序列。输入中允许使用空格,但应忽略。

表达式树是由 1 个字符的变量 A-Z 组成的序列,其子表达式树由括号 (expression_tree) 组成。示例:ABA(B C D)(AB)C((DE)F)

操作序列是一个字符串,带有字符R(反向)或S(简化)

Reverse 表示反转表达式树中所有内容的顺序。连续两次应用反向取消。 示例:(AB)C((DE)F) | R 应该打印 (F(ED))C(BA)

简化意味着删除表达式树及其每个子表达式树中第一个元素周围的括号。应用S 多次应该与应用S 一次具有相同的结果。 示例:(AB)C((DE)F) | S 应该打印 ABC(DEF)

输出:读取表达式树并将从左到右的操作顺序应用到表达式树,打印出不带字符的结果。

我最想知道的是如何建模表达式树来处理括号以及简化操作应该如何工作?

【问题讨论】:

标签: parsing tree expression


【解决方案1】:
'''
Examples are as follows :
INPUT:
(AB)(C(DE))/SS
(((AB)C)D)E/SS
(((AB)C)D)E/SR
(AB)C((DE)F)/SRS
(AB(CD((EF)G)H))(IJ)/SRS
(AB(CD((EF)G)H))(IJ)/SSSRRRS
(A(B(C)D)E(FGH(IJ)))/SRRSSRSSRRRSSRS
(A(BC(D(E((Z)K(L)))F))GH(IJK))/S
-------------------------------
OUTPUT:
AB(C(DE))
ABCDE
EDCBA
FEDCBA
JI(H(GFE)DC)BA
JI(H(GFE)DC)BA
JIHFGE(D(C)B)A
A(BC(D(E(ZK(L)))F))GH(IJK)/S
'''



'''
operationReverse function returns a reversed expression tree 
Example :  AB(CD) -> (DC)BA
'''
def operationReverse(expression):
    '''============== Reversing the whole expressions ================'''
    expression = expression[::-1] 
    expression = list(expression)

    '''========= Replace Closing brace with Opening brace and vice versa ========='''
    for x in range(0, len(expression)):
        if(expression[x] != ')' and expression[x] != '('):
            continue
        elif(expression[x] == ")"):
            expression[x] = "("
        else:
            expression[x] = ")"

    expression = ''.join(expression)
    return expression


'''
operationSimplify function returns a simplified expression tree 
Example :  (AB)(C(DE)) -> AB(C(DE))
operationSimplify uses recursion
'''
def operationSimplify(expression):

    '''========= If no parenthesis found then return the expression as it is because it is already simplified ========='''
    '''========= This is also the base condition to stop recursion ============='''
    if(expression.find('(')==-1):
        return expression


    '''If 1st character is opening brace then find its correspoinding closing brace and remove them and call the function by passing the values between the opening and                 closing brace'''

    if(expression[0] == '('):
        x = 1
        #numOfOpeningBrackets = maintains the count of opening brackets for finding it's corresponding closing bracket
        numOfOpeningBrackets = 1
        while(x < len(expression)):
            if(expression[x] != ')' and expression[x] != '('):
                x = x + 1
                continue
            elif(expression[x] == "("):
                numOfOpeningBrackets = numOfOpeningBrackets + 1
                x = x + 1
            else:
                numOfOpeningBrackets = numOfOpeningBrackets - 1   
                if(numOfOpeningBrackets == 0):
                    posOfCloseBracket = x
                    break         
                x = x + 1 
        expression = operationSimplify(expression[1:posOfCloseBracket]) + expression[posOfCloseBracket+1:]

    '''========= If no parenthesis found then return the expression as it is because it is already simplified ========='''
    if(expression.find('(')==-1):
        return expression

    '''========= Find the opening brace and it's closing brace and new expression tree will be concatenation of start of string till opening brace including the brace and string       with in the opening brace and closing brace passed as an argument to the function itself and the remaining string ========='''
    x = 0
    #numOfOpeningBrackets = maintains the count of opening brackets for finding it's corresponding closing bracket
    recursion = False
    numOfOpeningBrackets = 0
    while (x < len(expression)):
        if(expression[x] != ')' and expression[x] != '('):
                x = x + 1
        elif(expression[x] == "("):
            if(numOfOpeningBrackets == 0 or recursion == True):
                numOfOpeningBrackets = 0
                recursion = False
                posOfStartBracket = x
                y = x
            numOfOpeningBrackets = numOfOpeningBrackets + 1
            x = x + 1
        else:
            numOfOpeningBrackets = numOfOpeningBrackets - 1 
            if(numOfOpeningBrackets == 0):
                posOfCloseBracket = x 
                x = y 
                expression=expression[0:posOfStartBracket+1]+operationSimplify(expression[posOfStartBracket+1:posOfCloseBracket])+expression[posOfCloseBracket:]
                recursion = True
            x = x + 1
    return expression


'''
solution fucntion prints the final result  
'''
def solution(inputString):
    '''========= Remove the spaces from the input ==============='''
    #inputString = inputString.replace("\n","")
    inputString = inputString.replace(" ","")
    inputString = inputString.replace("\t","")
    #inputString = inputString.replace("()","")

    '''=============== The substring before '/' is expression tree and substring after '/' is sequence of operations  ======================'''

    #posOfSlash = Position Of Slash Character
    posOfSlash = inputString.find('/')
    if(posOfSlash == -1):
        print (inputString)
        return
    #expressionTree = Expression Tree
    expressionTree = inputString[0:posOfSlash]
    #seqOfOp = sequence of operations to be performed
    seqOfOp = inputString[posOfSlash+1:]

    '''============ If sequence Of Operations is empty then print the expression tree as it is ============== '''
    if(len(seqOfOp)==0):
        print(expressionTree)
        return


    '''============= Removing all the pairs of RR from the sequence Of Operations =================='''   
    seqOfOp = seqOfOp.replace(r+r,'')

    '''============ All mulptiple S are replaced by one single S ================'''   
    while(seqOfOp.find(s+s) != -1):
        seqOfOp = seqOfOp.replace(s+s,s)

    '''============ If to perform operation R then call operationReverse() else if to perform operation S call operationSimplify() ================'''
    for x in range (0 , len(seqOfOp)):
        if(seqOfOp[x] == r):
            expressionTree = operationReverse(expressionTree)
        else :
            expressionTree = operationSimplify(expressionTree)
    print(expressionTree)
    return



'''======= Global variables r and s representing operations R and S'''
r = 'R'
s = 'S' 
while True:
    try:
        inputString = input()
        '''==================== Calling function solution  ======================'''
        solution(inputString)
    except EOFError:
        break

【讨论】:

  • 哦……其实我现在不记得了……我一年前就解决了
猜你喜欢
  • 1970-01-01
  • 2010-09-19
  • 1970-01-01
  • 1970-01-01
  • 2020-09-12
  • 1970-01-01
  • 1970-01-01
  • 2011-04-11
  • 1970-01-01
相关资源
最近更新 更多