Parentheses pairing ({}[]()<>) issue

前端 未结 9 1788
醉酒成梦
醉酒成梦 2021-02-06 00:27

I want to be able to pair up all parentheses in a string, if they aren\'t paired then then they get their index number and False. It seems like it is repeating some values over

9条回答
  •  天命终不由人
    2021-02-06 00:48

    The below code will display the missing parentheses and the no of times missing in the given string.

    from collections import Counter
    
    def find_missing(str):
        stack1 = []
        stack2 = []
        result = []
        res_dict = {}
        open_set = '<[{('
        closed_set = '>]})'
        a = list(str)
        for i in a:
            if i in open_set:
                stack1.append(i)
            elif i in closed_set:
                stack2.append(i)
        dict1 = Counter(stack1)
        dict2 = Counter(stack2)
        print(dict1)
        print(dict2)
        for i in open_set:
            if dict1[i] > dict2[closed_set[open_set.index(i)]]:
                res_dict[closed_set[open_set.index(i)]] = dict1[i] - dict2[closed_set[open_set.index(i)]]
                result.append(closed_set[open_set.index(i)])
        for i in closed_set:
            if dict2[i] > dict1[open_set[closed_set.index(i)]]:
                res_dict[open_set[closed_set.index(i)]] = dict2[i] - dict1[open_set[closed_set.index(i)]]
                result.append(open_set[closed_set.index(i)])
        return res_dict
        # return result
    
    if __name__ == '__main__':
        str1 = '{This ((()bracket {[function]} < crazy}'
        x = find_missing(str1)
        if len(x) > 0:
            print("Imbalanced")
            print(x)
        else:
            print("Balanced")
    

提交回复
热议问题