反向波兰表达 - 监控输入

时间:2016-11-12 16:31:15

标签: python expression postfix-notation

所以我有代码使反向波兰语表达工作

def rpn(x):
    stack = []
    operators=['+', '-', '*']

    for i in x.split(' '):
        if i in operators:
            op1 = stack.pop()
            op2 = stack.pop()
            if i=='+': result = op2 + op1
            if i=='-': result = op2 - op1
            if i=='*': result = op2 * op1
            stack.append(result)
        else:
            stack.append(float(i))

    return stack.pop()


x = str(input("Enter a polish expression:"))
result = rpn(x)
print (result)

但是,我正在努力解决如何为特定输入提供一些错误消息 目前,只有在每个值后面都有一个空格时,此代码才有效。 3 4 +然后生病得到7的结果

但我想这样做,或者

- 自动移除间距

或代码只能在没有间距的情况下工作,如果有间距则提供错误 我想到了添加代码

的代码
if x contains " ":
   print("error")

我正在尝试解决的第二个问题是限制使用的运算符 所以它只会运行代码,如果它有数字和3个运算符(+, - ,*),如果有任何其他运算符或字母,它将显示错误。我再次想到它将是

if x contains something other than "integers and +,-,*:
     then print an error

我再次提出了概念,但没有关于如何执行它的python关键词知识。

1 个答案:

答案 0 :(得分:1)

您应该使用x.split()代替x.split(' '),它会从x中提取除split()之外的所有内容。

split(' ')将多个连续的空格视为一个空格(因此为一个分隔符),而>>> print(' '.split(' ')) ['', '', '', ''] >>> print(' '.split()) [] 将一个空格视为一个分隔符。

这就是区别:

for i in (_ for _ in x if not _.isspace()):
    # your algorithm

鉴于您的代码只处理一位数字:

for i in (_ if not _.isspace() else None for _ in x):
    if i is None:
        raise ValueError("Error!")
    # your algorithm here

如果您想提出错误:

# generate all combinations of N items
def powerSet(items):
    N = len(items)
    # enumerate the 2**N possible combinations
    for i in range(2**N):
        combo = []
        for j in range(N):
            # test bit jth of integer i
            if (i >> j) % 2 == 1:
                combo.append(items[j])
        yield combo