Posted on:

20 Jun 2023

0

Balanced_Bracket my solution

string = '[]{()}'


def balanced_string(string):
    balanced = False
    stack = []
    bracket_dict = {'{':'}', '[':']','(':')'}
    
    for char in string:        
        #if opening bracket then append to stack
        if char in bracket_dict.keys():
            stack.append(char)
            
        #if nothing in stack or the char is not closing bracket of the last char in stack
        elif char in bracket_dict.values():
            if stack == [] or bracket_dict[stack[-1]] != char:
                balanced = False
                return balanced
            else:
                 stack.pop()
                 
        #if its neither opening or closing bracket
        else:
            balanced = False
            return balanced
        
        #if stack is empty then its balanced
        if stack == []:
            balanced = True
    
    return balanced


print(f'balanced string function {balanced_string(string)}')

0 answers ( 0 marked as helpful)

Submit an answer