+ 2
(Python) Valid Parentheses
Input a string called “s” and if the string is a valid parentheses, output True or else output False. Could someone help me revise my code as below in the answer zone? e.g. input ((()())); output True. Input ((; output False. I’m very grateful for any helping hand.
12 ответов
+ 2
Xan
Yeah, that is intuitive, but... If somehow you happen to be using billions of '(', then you may overflow you variable. not that it really matters, but I had to point it out. theoretically, tho, it should loop back again to the positive with the same number, so it should actually work anyways. 🤔
Interesting.
+ 2
if s.count ("(")==s.count (")") and s.startswith ("(") and s.endswith(")"):
print ("valid")
else:
print ("invalid:)
+ 2
Manuel Maier
You're talking about a string being as long as you want?
You still need a count variable
+ 1
I understand the concept more. Thank you guys so much!
0
def ValidParentheses(s):
s=str(input())
if len(s)%2==0:
c=0
d=0
a=0
b=0
for i in s and k in range(len(s)):
if i==str("(") in s[:k]:
c+=1
if i==str(")") in s[:k]:
d+=1
for i in s:
if i ==str("("):
a+=1
if i==str(")"):
b+=1
if c>=d and a==b:
return True
else:
return False
0
I think there is a simpler algorithm:
count = 0
if you see an open bracket then count++;
if you see a close bracket then count--
Return true if both these were true:
1) Once processing has finished, count should equal zero
2) Count never went below zero
CASE 1:
(()()(()))
+1 +1 -1 +1 -1 +1 +1 -1 -1 -1
1 2 1 2 1 2 3 2 1 0
[All good]
CASE 2:
))((
-1 -1 +1 +1 = 0
[This ends correctly with 0, meaning same number of open to close brackets, BUT the syntax is wrong]
Completed code:
https://code.sololearn.com/cJMC3gAAxKYC/#py
0
J.G. In Python the size of an integer is not a problem because they could be as large as the memory in your computer allow it.
0
Picking up on the theoretical limitations is a pointless debate. To do this properly, we'd build a proper parser. The question is at beginner's level, and therefore so is the answer.
0
J.G. Also integers have no fixed limit in python. And yes Xan is right, this is not the problem in this task. I think the solution from Pedro Demingos is the best.
- 1
Mitali, your code will think this example is valid: "())(()"
That's why the nesting count is needed, see:
https://code.sololearn.com/cJMC3gAAxKYC/#py