首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >验证包含太多运算符的后缀

验证包含太多运算符的后缀
EN

Stack Overflow用户
提问于 2019-06-30 06:56:27
回答 3查看 107关注 0票数 1

我正在计算一个后缀表达式,我需要它来说明如果一个接一个的运算符太多,表达式就不能被计算。我知道堆栈中将没有任何内容,因此无法计算它,但我不知道如何在我的代码中添加它。

我只在这里添加了我认为是必要的代码。如果代码能保持相对相似,那就太好了。

编辑:它现在只是说任何东西都不能被评估

代码语言:javascript
运行
复制
def process(testline,count):
    k=[]

    for i in range(0,len(testline),1): 
        if(testline[i].isdigit() == True): 
            k.append(float(testline[i]))

        else:
            try:
                x = j.pop()
                y = j.pop()
            except IndexError:
                break

        if (testline[i]=='*'): 
            ans = x * y
            k.append(ans)

        elif (testline[i]=='+'):
            ans = x + y
            k.append(ans)

        elif (testline[i]=='-'):
            ans = x - y
            k.append(ans)

        elif (testline[i]=='/'):
            ans = x / y
            k.append(ans)

        else:
            print("Line",count,"is not able to be evaluated")
            return

    if len(k) != 1:
        print("Line",count,"is not able to be evaluated")
    else:
        print ('Line',count,'result is',k[0])
        return

    print('Line',count,'result is',k[0])

现在,输出是:

代码语言:javascript
运行
复制
    Line 1 is not able to be evaluated
    Line 2 is not able to be evaluated
    Line 3 is not able to be evaluated
    Line 4 is not able to be evaluated

输入为:

代码语言:javascript
运行
复制
    295+*3-
    61*7-4*
    61*79-15*
    6a*7-b*
    623-+*-1
EN

回答 3

Stack Overflow用户

发布于 2019-06-30 07:18:40

您可以将您的pop移到迭代的开始处,并用try/except包围,以检查您是否可以弹出:

代码语言:javascript
运行
复制
for i in range(0,len(testline),1): 
    if(testline[i].isdigit() == True): 
        k.append(float(testline[i]))

    else:
        try:
            x = k.pop()
            y = k.pop()
        except IndexError:
            break

        if (testline[i]=='*'): 
            ans = x * y
            k.append(ans)

        elif (testline[i]=='+'):
            ans = x + y
            k.append(ans)

        elif (testline[i]=='-'):
            ans = x - y
            k.append(ans)

        elif (testline[i]=='/'):
            ans = x / y
            k.append(ans)

        else:
            print("Line",count,"is not able to be evaluated")
            return

为了使它更健壮,并且不需要添加那些额外的appends,我将这样做:

代码语言:javascript
运行
复制
operators = {'*': lambda x ,y: x * y,
             '/': lambda x, y: x / y,
             '+': lambda x, y: x + y,
             '-': lambda x, y: x - y}

for c in testline:
    if c.isdigit(): 
        k.append(float(c))

    elif c in operators:
        try:
            x = k.pop()
            y = k.pop()
        except IndexError:
            break
        ans = operators[c](x, y)
        k.append(ans)

    else:
        print("Line",count,"is not able to be evaluated")
        return

编辑:更简单:

代码语言:javascript
运行
复制
operators = {'*': lambda x ,y: x * y,
             '/': lambda x, y: x / y,
             '+': lambda x, y: x + y,
             '-': lambda x, y: x - y}

for c in testline:
    if c.isdigit(): 
        k.append(float(c))

    else:
        try:
            x = k.pop()
            y = k.pop()
            ans = operators[c](x, y)
            k.append(ans)
        except IndexError:  # Couldn't pop... (empty stack)
            break
        except KeyError:  # char is not a digit and not an operator
            print("Line",count,"is not able to be evaluated")
            return
票数 0
EN

Stack Overflow用户

发布于 2019-06-30 08:37:06

根据OP希望保持原始代码尽可能不变的愿望,这里有一个代码的版本,它可以用最少的更改来工作。主要的改变是在每次算术运算之前增加对操作数数量不足的检查,这也是OP特别询问的。此代码还在必要时颠倒了计算中的操作数顺序:

代码语言:javascript
运行
复制
def process(testline,count):

    k=[]

    for i in range(0,len(testline),1):
        if(testline[i].isdigit() == True):
            k.append(float(testline[i]))

        elif (testline[i]=='*'):
            if len(k) < 2:
                print("Line", count, "is not able to be evaluated. not enough operands")
                return
            x = k.pop()
            y = k.pop()
            ans = x * y
            k.append(ans)

        elif (testline[i]=='+'):
            if len(k) < 2:
                print("Line", count, "is not able to be evaluated. not enough operands")
                return
            x = k.pop()
            y = k.pop()
            ans = x + y
            k.append(ans)

        elif (testline[i]=='-'):
            if len(k) < 2:
                print("Line", count, "is not able to be evaluated. not enough operands")
                return
            x = k.pop()
            y = k.pop()
            ans = y - x    # << reversed operands
            k.append(ans)

        elif (testline[i]=='/'):
            if len(k) < 2:
                print("Line", count, "is not able to be evaluated. not enough operands")
                return
            x = k.pop()
            y = k.pop()
            ans = y / x   # << reversed operands
            k.append(ans)

        else:
            print("Line",count,"is not able to be evaluated")
            return

    if len(k) != 1:
        print("Line",count,"is not able to be evaluated")
        return

    print('Line',count,'result is',k[0])

使用此测试代码:

代码语言:javascript
运行
复制
lines = [
    '295+*3-',
    '61*7-4*',
    '61*79-15*',
    '6a*7-b*',
    '(-1)*2',
    '623-+*-1',
]

for i in range(len(lines)):
    process(lines[i], i + 1)

结果输出为:

代码语言:javascript
运行
复制
('Line', 1, 'result is', 25.0)
('Line', 2, 'result is', -4.0)
('Line', 3, 'is not able to be evaluated')
('Line', 4, 'is not able to be evaluated')
('Line', 5, 'is not able to be evaluated')
('Line', 6, 'is not able to be evaluated. not enough operands')
票数 0
EN

Stack Overflow用户

发布于 2019-06-30 15:39:15

这是我的版本,它很像@Tomrikoo的第二个版本,但提供了一个完整的答案,并解决了原始代码中的一些额外问题。这段代码在所有情况下都会打印结果或错误,并在有效答案或无效堆栈条件(堆栈上有多个项)的情况下处理最终状态。另外,我颠倒了操作数的应用顺序(我假设'42/‘应该产生2,而不是像我所有的HP计算器那样产生0.5 ):

代码语言:javascript
运行
复制
def process(testline, count):

    operations = {
        '+': lambda x, y: y + x,
        '-': lambda x, y: y - x,
        '*': lambda x, y: y * x,
        '/': lambda x, y: y / x,
    }

    k = []

    for c in testline:

        if c.isdigit():
            k.append(float(c))

        elif c in operations:
            if len(k) < 2:
                print("Line {}: bad expression '{}' (not enough operands)".format(count, testline))
                return
            k.append(operations[c](k.pop(), k.pop()))

        else:
            print("Line {}: unexpected character '{}' in expression '{}'".format(count, c, testline))
            return

    if len(k) != 1:
        print("Line {}: bad expression '{}' (too many operands)".format(count, testline))
    else:
        print("Line {}: Result: '{}' = {}".format(count, testline, k[0]))


lines = [
    '295+*3-',
    '61*7-4*',
    '61*79-15*',
    '6a*7-b*',
    '(-1)*2',
    '623-+*-1',
]

for i in range(len(lines)):
    process(lines[i], i + 1)

输出:

代码语言:javascript
运行
复制
Line 1: Result: '295+*3-' = 25.0
Line 2: Result: '61*7-4*' = -4.0
Line 3: bad expression '61*79-15*' (too many operands)
Line 4: unexpected character 'a' in expression '6a*7-b*'
Line 5: unexpected character '(' in expression '(-1)*2'
Line 6: bad expression '623-+*-1' (not enough operands)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56821370

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档