using python 3 stacks to ensure symbols match in c

2019-02-28 19:07发布

def spc(sym):
    stk1=myStack()
    stkall=myStack()
    for i in sym:
        if i not in stk1:
            stk1.push(i)
        else:
            stkall.push(i)
    for j in stk1:
        for k in stkall:
            if j==k:
                stk1.pop(j)
                stkall.pop(k)
            else:
                pass
    if len(stk1) == len(stkall):
        print("all symbols match")
    else:
        print(("these symbols, %s,  have no matches")%(stkall))

Above code gives me this error
"TypeError: argument of type 'myStack' is not iterable"

But I fixed it by the answer from @SergeBallesta. After I edited code to look as you see now.

Now im getting this error:

"return self.container.pop(item) # pop from the container, this was fixed from the old version which was wrong TypeError: 'str' object cannot be interpreted as an integer"

What i want to achieve is for parenthesis and all symbols to be properly balanced in that not only does each opening symbol have a corresponding closing symbol, but the types of symbols match as well.

Code for my Stack class is below. Please assist to implement this using STACKS

class myStack:
    def __init__(self):
        self.container = []
    def isEmpty(self):
        return self.size() == 0
    def push(self, item):
        self.container.append(item
    def pop(self, item):
        return self.container.pop(item)
    def size(self):
        return len(self.container)  # length of the container

    def __iter__(self):
        return iter(self.container)

2条回答
不美不萌又怎样
2楼-- · 2019-02-28 19:59

To do bracket validation using a stack, we only need one stack. As we come across opening brackets, we push them onto the stack. When we come across a closing bracket, we pop the top opening bracket off the stack, and compare the two. If they are the same bracket type, we continue, otherwise the string is invalid. If we ever try to pop an empty stack, the string is invalid. If we reach the end of the string without clearing the stack, the string is invalid.

opening = '[{<('
closing = ']}>)'

d = dict(zip(opening, closing))

def validate(s):
    stack = []
    for c in s:
        if c in opening:
            stack.append(c)
        elif c in closing:
            if not stack:
                # tried to pop empty stack
                return False
            popped = stack.pop()
            if d[popped] != c:
                # bracket mismatch
                return False
    return not stack
查看更多
倾城 Initia
3楼-- · 2019-02-28 20:08

These lines

if i not in stk1:

and

for j in stk1:

requires myStack to be iterable. In Python it means that it shall have an __iter__ method that returns an iterator on its objects. As you already have an internal container, the __iter__ method can be as simple as:

class myStack:
    ...
    def __iter__(self):
        return iter(self.container)
查看更多
登录 后发表回答