I have written the below code in Python but I am getting errors on the array 'stack' every time it says stack apart from the initial assignment. The error is "Instance of 'list' has no 'push' member".
To clarify, this piece of code is to run through each character and check if it is an opening bracket. It will push into stack, the opening bracket and I will match via an if/else statement to see if the they are matching pairs. If it does not match, return false.
Does anyone know why this code is giving errors on the stack? Stacks are very new to me and they are not making sense. This is the first piece of code I have written in Python so there may be an error in my syntax too.
I have taken the suggestion of the code from a video on stacks and tried to translate it into python to see it working. The code they were using was just a guideline of what should happen.
str = '()[(]())'
arr = ['(','[']
stack = []
for char in str:
if char in arr:
stack.push(char)
else:
if stack.empty():
top = stack.pop()
break
if(top == '[' and char != ']') or (top == '(' and char != ')'):
break
return stack.empty()
stras variable name. You may confuse it withstr().push()method on list. Useappend()insteadpushandemptyin listlisttype has neither apushnor anemptymethod. Why do you think this should work? What do you think istopin the finalifstatement?