python作业5——消消乐

相邻的组合两两相消去,最后是否能消完

str = "{[()]{}[[]]}[()]"

def search(a, lst): # 寻找元素是否在列表中,并返回index
    for i in range(len(lst)):
        if lst[i] == a:
            return i
    else:
        return  False

def check(str): # 判断是否可消完
    open_bracket = ['(', '[', '{']
    close_bracket = [')', ']', '}']
    lst = [] # 存储已经消去的元素的index
    while len(lst) != len(str):
        stack = []
        for i in range(len(str)):
            if i in lst: # 判断是否已消去
                continue
            if str[i] in open_bracket:
                stack.append(str[i])
                b = i
            elif str[i] in close_bracket:
                if len(stack) > 0:
                    a = stack.pop() # a的index为b
                    stack = []
                    idx1 = search(a, open_bracket)
                    idx2 = search(str[i], close_bracket)
                    if idx1 == idx2:
                        lst.append(b) 
                        lst.append(i) # 将符合消去标准的符号索引存入列表
                        break
                    if idx1 != idx2: # 不符合消去标准,继续找下一个开括号
                        continue
                else:
                    return False
            else:
                return False
    return True

# main
if check(str):
    print("yes")
else:
    print("not")

你可能感兴趣的:(py作业,python)