如何更正括号的添加以不必要地使用括号python3

Posted

技术标签:

【中文标题】如何更正括号的添加以不必要地使用括号python3【英文标题】:How to correct addition of parentheses to not use parentheses unnecessarily python3 【发布时间】:2019-12-05 08:06:28 【问题描述】:

我正在制作一个将前缀转换为中缀的程序,但在将括号放入表达式时遇到问题。 对于转换,我使用经典的堆栈算法。这是我的括号函数。

    输入:

    //+86 16 67/*/31 53 85 15 
    

    我的输出:

    ((86+16)/67)/(((31/53)*85)/15)
    

    预期输出:

    (86+16)/67/(31/53*85/15)
    
def breckets(operand1, operand2, operace):
res = ""
if (operand1.isdigit()) and (operand2.isdigit()):
    res = operand1 + operace + operand2
elif (operand1.isdigit()) and (not operand2.isdigit()):
    if operace == "+":
        res = operand1 + operace + operand2
    else:
        res = operand1 + operace + "(" + operand2 + ")"
elif (not operand1.isdigit()) and (operand2.isdigit()):
    if prior(operace) != 0:
        res = "(" + operand1 + ")" + operace + operand2
    else:
        res = operand1 + operace + operand2
else:
    res = "(" + operand1 + ")" + operace + "(" + operand2 + ")"
return res
def prior(a):
    prior = None
    if a in "+-":
        prior = 0
    elif a in "*/":
        prior = 1
    elif a in "^":
        prior = 2
    else:
        print("Something went wrong")
        exit()
    return prior

但是我不能不必要地使用括号,有人可以给我一些建议吗?

【问题讨论】:

请使用一些输入数据、您的代码得到的输出和预期的输出添加对函数的调用。 函数的返回值会被用作花括号函数的操作数吗?除了两个操作数都是数字外,返回值是否应该总是在括号外? 你想得到类似:(E^F), D, / >>> (D/(E^F)) 吗? @ShengZhuang 不,只有在必要时才需要放括号。所以它应该没有外括号 @ShengZhuang 尝试将其放入计算器...没有括号它有错误的答案) 【参考方案1】:

下面的代码可以得到你所期望的。但我不确定算法是否正确,因为我不熟悉数据结构。

我使用一个基本函数对列表进行了多次排序,而不是严格地从右到左对列表进行排序,您可以更改一些行来打破 while 循环以使其成为您想要的。

无论如何希望这可以帮助你。

operators = "+-*/^"
# presume the input is a finely spaced str that can be splitted into a proper list
# ipt = "/ * + 86 16 67 / * / + 31 53 85 15 / / 33 45 74"  # for testing
ipt = "/ / + 86 16 67 / * / 31 53 85 15"  
ip = ipt.split()


def sorting(lst):
    res = []
    i = len(lst)-1  # check list items from right to left
    while i >= 0:
        if i >= 3:
            if lst[i-2] in operators:
                # check if the operator is followed by two numbers
                if lst[i-1] not in operators and lst[i] not in operators: 
                    # check if the operator is + | -, the result should be in parentheses
                    if lst[i-2] in "+-":
                        res.append("(" + lst[i-1] + lst[i-2] + lst[i] + ")")
                        i -=3
                        continue
                    # if the operator is following another operator, the result shouldn't be in parentheses
                    if lst[i-3] in operators:
                        res.append(lst[i-1] + lst[i-2] + lst[i])
                        i -=3
                        continue
                    # if the operator is following a number, the result shouldn be in parentheses
                    else:
                        res.append("(" + lst[i-1] + lst[i-2] + lst[i] + ")")
                        i -= 3
                        continue
        # this is to check the first item of the list is an operator and followed by two numbers
        elif i == 2:
            if lst[i-2] in operators:
                if lst[i-1] not in operators and lst[i] not in operators:
                    res.append(lst[i-1] + lst[i-2] + lst[i])
                    i -=3
                    continue
        res.append(lst[i])
        i -= 1
    # as all items are appending to the new list, so the positions are totally reversed
    return list(reversed(res))

def no_more_operators(lst):
    # to check if the lst is sortable
    # one scenario is there are exccesive numbers, but no operators
    # the current function can only check if any operators is in the list
    for op in operators:
        if op in lst:
            return False
    return True

def no_more_numbers(lst):
    # to check if the lst is sortable
    # one scenario is there are exccesive operators, but no numbers
    # the current function can only check if any number is in the list
    for i in lst:
        if i.isnumeric():
            return False
    return True

# keep sorting the list until there is no more numbers or n0 more operators
while not no_more_numbers(ip) or not no_more_operators(ip):
    ip = sorting(ip)
    print(ip)

输出:

['/', '/', '(86+16)', '67', '/', '*', '31/53', '85', '15']
['/', '(86+16)/67', '/', '31/53*85', '15']
['/', '(86+16)/67', '(31/53*85/15)']
['(86+16)/67/(31/53*85/15)']

【讨论】:

嗯,这比我的解决方案好,但是(它肯定比我的代码短),但它不适用于像这样的输入示例:/49-/34 74-17/69 78 output '49/ (34/74-(17-(69/78)))' 预期输出:49/(34/74-(17-69/78))

以上是关于如何更正括号的添加以不必要地使用括号python3的主要内容,如果未能解决你的问题,请参考以下文章

数组(结构类型)的 Where 是不是已优化以避免不必要地复制结构值?

如何使用 Python3 删除括号和所有数据

pycharm中使用正则表达式批量添加print括号

不必要地将函数标记为暂停以支持通用抽象

美化 C++ 代码以在条件语句中添加括号

Gradle 能否以一种不会不必要地触及输出文件的方式生成 POM?