def balanced(string): """ Takes a string and returns the index of the first brace that breaks its balance. Balanced string returns -1 """ stack = [] position = -1 #assumption: empty string is balanced if len(string) == 0: return position #catching single character cases elif ((len(string) == 1) and (string =="{" or string == "}")): return 0 for i in range(len(string)): char = string[i] if char == "{": #appended character and index - need to keep track of the { stack.append([char,i]) elif char == "}": #check for empty stack otherwise pop doesn't work if ((len(stack) == 0) or (stack.pop()[0] != "{")): return i #consecutive left bracket heavy cases if len(stack) != 0: return stack[0][1] return position def unitTest(expected, test): return ('Expected: ', expected, 'Test: ', test, 'Result: ',(expected == test)) def main(): # -1 cases print unitTest(-1,balanced("")) print unitTest(-1,balanced("hello world")) print unitTest(-1,balanced("{}")) print unitTest(-1,balanced("{{}{}}")) print unitTest(-1,balanced("{}{{}{{{}}}}")) print unitTest(-1,balanced("a")) print "\n" # 0 cases print unitTest(0,balanced("}push{")) print unitTest(0,balanced("}")) print unitTest(0,balanced("{")) print unitTest(0,balanced("}}}}}")) print unitTest(0,balanced("{{}{{{}{{")) print "\n" # greater than 0 cases print unitTest(7,balanced("{{abc}}}}}")) print unitTest(9,balanced("{{{abc}}}}}}")) print unitTest(2,balanced("{}{foo{}")) print unitTest(10,balanced("{}{}{}{}{}{")) print "\n" main()
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question