python比较来自用户输入的括号并确保它们有一对

Geo*_*ris 1 python

我正在编写一个程序,用来输入括号的用户输入,即{} [](),并检查它们是否有一对(打开和关闭).我在运行代码时遇到错误,我总是得到返回false.我已经尝试了不同的方法来检查预先设置的"列表"但它似乎不起作用.我也必须使用上面的课程.任何帮助表示赞赏.

一些示例输入是:

    >>>parenthesesMatch('{[]}')
    True
    >>>parenthesesMatch('({})')
    True
    >>>parenthesesMatch('{[)]}')
    False
Run Code Online (Sandbox Code Playgroud)

我的代码:

    #George flamburis


class Stack():
def __init__(self,que=[]):
    self.lst = que
def __repr__(self):
    return "Stack({})".format(self.lst)
def push(self, add):
    self.lst.append(add)
def pop(self):
    return self.lst.pop()
def isEmpty(self):
    return self.lst==[]
def first(self, loc=0):            #naming of this method can't be []
    return self.lst[loc]
def len(self):
    return len(self.lst)

def parenthesesMatch(match):
     s = Stack()
     end = []
     for char in match:
         if char in "[ { (":
             s.push(char)
         else:
             end.append(char)

     if s.len()==len(end):
             for num in range(len(end)):
                     if s.first(num) and end[num] not in '[]' or '{}' or'()':
                             return False
             return True
     elif s.len()!=len(end):
             return False
Run Code Online (Sandbox Code Playgroud)

che*_*ner 6

当你看到一个关闭字符时,简单地尝试从堆栈中弹出一个关闭字符要容易得多,如果不可能则会失败.

pairs = dict(tuple(pair) for pair in ["()", "[]", "{}"])
# pairs["("] == ")"
# pairs["["] == "]"
# etc
def parenthesesMatch(match):
    s = Stack()
    for char in match:
        # Not "] } )"
        if char in pairs.values() and pairs[s.pop()] != char:
            return False
        elif char in pairs:
            s.push(char)
    return s.isEmpty()
Run Code Online (Sandbox Code Playgroud)