计算Python中不平衡的括号。如何改善我的代码?

时间:2019-01-12 19:54:11

标签: python

我听说算不平衡括号程序对于初学者来说是一项很好的知识验证任务。所以我写了一个。它可以完成工作,但可以做得更好。有人可以给我任何提示(不直接回答)我可以改善什么?有没有办法像我一样设置一个通用正则表达式而不是4?

import re
lstCH = ['<','>','(',')','[',']','{','}']   # List of allowed characters

def isbr(string):                           #To make sure that string consists only of characters in lstCH
    for x in range(len(string)):
        if string[x] in lstCH:
            continue
        else:
            return False
    return True

def eliminate(string, Search_Method):       #function that 'strips' line(string) out of characters that match regular expression(Search_Method)
    tab = list(string)
    while 1:
        ko = Search_Method.search(string)
        if ko != None:
            del tab[ko.end()-1]
            del tab[ko.start()]
            string = ''.join(str(x)for x in tab)
        else:
            break
    return string

RegEx1 = re.compile(r'''#Regular expressions that match closed pairs of brackets with whatever inside
(
\<
(.*)*
\>
)
''',re.VERBOSE)
RegEx2 = re.compile(r'''
(
\(
(.*)*
\)
)
''',re.VERBOSE)
RegEx3 = re.compile(r'''
(
\[
(.*)*
\]
)
''',re.VERBOSE)
RegEx4 = re.compile(r'''
(
\{
(.*)*
\}
)
''',re.VERBOSE)
while 1:             #main loop
    print("Enter a line(or press Ctrl+C to exit): ", end='')
    try:
        string = input()
        if isbr(string)==False:
            print('You have entered characters other than brackets.')
            continue
        result = eliminate(eliminate(eliminate(eliminate(string,RegEx1),RegEx2),RegEx3),RegEx4) ##Nesting eliminate function inside itself with different 2nd parameter at each level. One type of brackets at a time :/
        if len(result)==1:                      #result is a string that consists of brackets with no pair. Lenght of that string is my solution
            print("There is 1 missing bracket")
        else:
            print("There are %d missing brackets"%len(result))
    except KeyboardInterrupt:
        print("Bye!")
        break

0 个答案:

没有答案