查找文件中的括号对和匹配数量的总和

时间:2015-02-03 05:02:17

标签: python python-3.x

如果语句中的括号匹配或不匹配,我创建了两个函数来返回True / False。我的问题是如何使用它不仅可以打开和读取文件,还可以计算匹配对和状态的数量,如果所有对匹配的话。这是我的下面的代码:(同样,导入的堆栈只是我创建的一个简单的类堆栈)

from stack import Stack
def parChecker(symbolString):
    s = Stack()
    balanced = True
    index = 0
    while index < len(symbolString) and balanced:
        symbol = symbolString[index]
        if symbol in "([{":
            s.push(symbol)
        else:
            if s.is_empty():
                balanced = False
            else:
                top = s.pop()
            if not matches(top,symbol):
                balanced = False
        index = index + 1
    if balanced and s.is_empty():
        return True
    else:
        return False

def matches(open,close):
    opens = "([{"
    closers = ")]}"
    return opens.index(open) == closers.index(close)


parenthesis= "()()(((("
print(parChecker(parenthesis))

我需要它来返回这样的东西:

Enter the file name: test1.py

    () pairs: 2
    {} pairs: 1
    [] pairs: 2
    All () matched.
    Not all {} matched.
    All [] matched.

0 个答案:

没有答案