+ 2
Balanced parentheses — python — help
I'm using the following code for the practice. I do not understand why it outputs "None", as well as the value through the **print()** function. Python Data Structure — Lesson 28 Any explanations? def balanced(expression): count1 = 0 count2 = 0 for i in expression: if i == "(": count1 += 1 elif i == ")": count2 += 1 if count1 == count2: print("True") else: print("False") print(balanced(input()))
10 ответов
+ 3
print(balanced(input())) if didt input something, count1 will 0 and count2 the same
you are get output True cause
if count1 == count2:print("True")
0==0 true print true,
and after you get output None cause
balanced func without return.. return nothing..None, ok? 🧐
+ 2
Parentheses are balanced, if all opening parentheses have their corresponding closing parentheses.
Given an expression as input, we need to find out whether the parentheses are balanced or not.
For example, "(x+y)*(z-2*(6))" is balanced, while "7-(3(2*9))4) (1" is not balanced.
The problem can be solved using a stack.
Push each opening parenthesis to the stack and pop the last inserted opening parenthesis whenever a closing parenthesis is encountered.
If the closing bracket does not correspond to the opening bracket, then stop and say that the brackets are not balanced.
Also, after checking all the parentheses, we need to check the stack to be empty -- if it's not empty, then the parentheses are not balanced.
Implement the balanced() function to return True if the parentheses in the given expression are balanced, and False if not.
Sample Input:
(a( ) eee) )
Sample Output:
False
+ 2
Suppose the input was ")(()". The number of opening and closing parentheses is the same but the expression is not balanced.
+ 2
Do you know what is mean stack?
If not, https://en.wikipedia.org/wiki/Stack_(abstract_data_type)
st = input()
stack = []
try:
for u in st:
if u=="(":
stack.append(u)
if u==")":
stack.pop()
print("True")
except:
print("False")
...etc
after you need check out stack if zero ok, if there has somthing, false, you can use len func for that..
len(stack)==0..ok else false..
of course this task can do some very easy way, i just want to show about stack
p.s. use try except cause you will get error then will delete from empty stack
+ 2
Okay, thanks people!
+ 1
I tried what you said, now I have:
def balanced(expression):
count1 = 0
count2 = 0
for i in expression:
if i == "(":
count1 += 1
elif i == ")":
count2 += 1
if count1 == count2:
return True
else:
return False
print(balanced(input()))
All correct, appart from the last test case
+ 1
What the task
0
import inspect
def balanced(expression):
stack = []
for i in expression:
if i == "(":
stack.append(i)
elif i == ")":
if not stack:
return "False"
stack.pop()
if not stack:
return "True"
else:
return "False"
print(inspect.getsource(balanced))
I guess it need one statement will be process both