出现“ +”时如何取和?

时间:2019-02-07 23:03:50

标签: python string stack postfix-notation

我正在使用后缀表示法和堆栈,我想知道是否/如何在出现字符串'+'时求和列表,堆栈等元素?

在此示例中,我将仅使用列表而不是堆栈(尽管如果您有堆栈的解决方案,请务必继续)。

所以,也许我有:

hostvars['some_hostname']['ansible_uptime_seconds']

并将其转换为列表:

string = '1 2 3 +'

如果正确,则评估为:

['1','2','3','+']

这是我认为可以工作的方式(注意:我进行过的valid()函数检查是否可以将其更改为基于字符串的浮点型。工作正常):

6

我如何使它工作,以便如果存在'+'或'-'等,它将进行适当的操作?

注意:为简单起见,您可以假定运算符将始终位于结尾处。因此,不必担心类似“ 12 + 34 *”的问题,尽管如果您有解决方案,将不胜感激。

7 个答案:

答案 0 :(得分:3)

您使用堆栈评估后缀表示法。看到数字时,将其推入堆栈。当您看到运算符时,会弹出足够的数字来满足要求,然后推入结果。最后,纸叠应该只有一件,然后打印。

现在,+通常是二进制运算符:它需要两个操作数。在您的情况下,您希望它消耗堆栈中的所有内容。对于+来说,这是非常规的含义,但是实现起来很简单。

def postfix(tokens):
    stack = []
    tokens = tokens.split() if isinstance(tokens, str) else tokens
    for token in tokens:
        if token.isdigit() or token.startswith("-") and token[1:].isdigit():
            stack.append(int(token))
        elif token == "+":
            assert stack    # need at least one item
            result = 0
            while stack:
               result += stack.pop()
            stack.append(result)
        else:
            raise ValueError("invalid token {}".format(token))
    assert len(stack) == 1
    return stack[0]

print(postfix("1 2 3 +"))

此结构易于扩展以处理其他操作。例如,您可以使用+进行二进制加法,使用++进行总计。

elif token == "++":   # sum all
    result = 0
    while stack:
       result += stack.pop()
    stack.append(result)
elif token == "+":    # binary additon
    stack.append(stack.pop() + stack.pop())

答案 1 :(得分:1)

这里有几个问题。第一个是int(i)。这不会将i的副本创建为整数,但根本不会修改i。您追加到列表的i仍然是字符串。第二个问题是这不适用于两位数的数字-您立即将其追加到列表中,而不是跟踪可能的两位数数字。

解决这些问题:

def valid(i):
  return i.isdigit()

def post_fix(string):
  lst = [0]
  for i in string:
    if i == '(':
      continue
    elif i == ' ':
      lst.append(0)
    elif valid(i):      
      lst[-1] *= 10
      lst[-1] += int(i)
    elif i == '+':
      print(sum(lst))

post_fix('1 2 3 +')

输出:

6

答案 2 :(得分:0)

the_list = ['1','2','3','+'] 
if '+' in the_list:
    #do things related to it being present

我相信您甚至不需要将其转换为列表(尽管它可以使数字的后续处理更加容易)。像这样:

if '+' in '1 2 3 +':

也应执行,因为在pyton中将字符串视为可迭代的对象

答案 3 :(得分:0)

lst = string.split()
if '+' in lst:
    # Do addition
elif '-' in lst:
    # Do subtraction

答案 4 :(得分:0)

您不能只求和,因为列表是字符串格式,并且“ +”始终是字符串,所以:

if "+" in lst:
    total = sum([int(i) for i in lst if not i == "+"])

功能:

def sum_list(x):
    if "+" in x:
        total = sum([int(i) for i in x if not i == "+"])
    return total

答案 5 :(得分:0)

对于加法(+)是字符串的最后一个值的情况,请执行以下操作。您可以将其他条件添加到post_fix方法中,然后添加-,*,%等:

def post_fix(string):
    result = None
    split_string = string.split()
    if '+' == split_string[-1]:
        result = sum(map(int, filter(lambda x: x.isdigit(), split_string)))
    return result

只要弄不清楚这条线,就可以将其击穿:

filtered_digits = filter(lambda x: x.isdigit(), split_string)  # Checks if the string is a digit and adds it to the filtered_digits list
casted_to_int = map(int, filtered_digits)  # Casts all values found to be str representation of ints to int through the map function
result = sum(casted_to_int)  # sums our list of integers

答案 6 :(得分:0)

尝试这样做:

mystr = "1 2 3 4 +"
mylst = mystr.split() #converts the string to list:  ['1', '2', '3', '+']
nums = [ int(i) for i in mylst[:-1]] #list of numbers

if mylst[-1] == "+":  #check for the sign present at the end of the string/list
  print(sum(nums))

nums2 = ['1', '2', '3', '4']
print(sum(nums2))

如果符号不是末尾,请尝试使用以下列表理解方法将str转换为int:

nums = [ int(i) for i in mylst if i in "1234567890"]

这将防止在将元素转换为int以进行进一步计算时发生ValueError