I have a program that displays square brackets, '['
and ']'
. It displays them in random order and a random amount of times (up to 99).
The code below is my current code, it displays things like the following each time you run the module.
Input:
[[[[]]]]
[][]][]][[][]
[]]]][[[[[[]]][][][[]
My code:
import random
import string
def randomGen(N):
return random.randint(1,N)
char1 = '['
char2 = ']'
finalist = []
newList = []
newList2 = []
newValue = randomGen(99)
newValue2 = randomGen(99)
for i in range(newValue):
newList.append('[')
for j in range(newValue2):
newList2.append(']')
finalist = newList + newList2
for everChar in finalist:
print everChar,
I now want the program to tell the user whether the brackets displayed are balanced or unbalanced. By this I mean whether it consists of entirely nested pairs.
So '[][][]'
is balanced and '[]]][[]'
is unbalanced.
When my module is running I want it to display some text saying 'balanced'
or 'unbalanced'
in regards to the brackets.
I have added this to my code, I am not sure why it is not working but I think I am along the right lines:
def balanced(input):
opened = 0
for c in input:
if c == '[':
openend += 1
elif c == ']':
opened -= 1
if opened < 0:
print 'Not Balanced'
if opened > 0:
print 'Not Balanced'
if opened == 0:
print 'Balanced'
print opened
return opened == 0