Posted on:

21 Jul 2023

0

# My solution to the stacks challenge

Very dirty, very brute force, but here is my solution:

bal_list = list(input("Enter brackets to check for balance: ")) #Input initial brackets to be checked for balance.
if len(bal_list) % 2 == 1: #If the list of brackets is an odd number, it cannot be balanced.
print("Not Balanced")

elif len(bal_list) % 2 == 0:
half_length = len(bal_list)//2
if any(char in ['(', '{', '['] for char in bal_list[half_length:]): #The latter half of any list cannot be any of these characters
print("Unbalanced")
elif any(char in [')', '}',']'] for char in bal_list[:half_length]): #The former half of any list cannot be any of these characters
print("Unbalanced")
elif bal_list[(int(len(bal_list)/2)-1)] == '(' and bal_list[int(len(bal_list)/2)] == ')': #The innermost of any list must be round brackets
print('Balanced')
elif bal_list[0] == '{' and bal_list[len(bal_list)-1] == '}': #'{' and '}' can only be on the outside of any balanced list
print("Balanced")
elif bal_list[(int(len(bal_list)/2)-1)] == '[' and bal_list[int(len(bal_list)/2)] == ']': #Provided there are no round brackets, [] can be the innermost brackets
print('Balanced')
else:
print("Unbalanced") #anything not covered already is unbalanced