+ 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.

3rd Apr 2018, 11:46 AM
Vicky Kuo
Vicky Kuo - avatar
12 RĂ©ponses
3rd Apr 2018, 10:59 PM
Pedro Demingos
Pedro Demingos - avatar
+ 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.
3rd Apr 2018, 12:04 PM
J.G.
J.G. - avatar
+ 2
if s.count ("(")==s.count (")") and s.startswith ("(") and s.endswith(")"): print ("valid") else: print ("invalid:)
3rd Apr 2018, 12:12 PM
Mitali
Mitali - avatar
+ 2
Manuel Maier You're talking about a string being as long as you want? You still need a count variable
4th Apr 2018, 12:02 AM
J.G.
J.G. - avatar
3rd Apr 2018, 12:08 PM
Emma
+ 1
I understand the concept more. Thank you guys so much!
3rd Apr 2018, 12:24 PM
Vicky Kuo
Vicky Kuo - avatar
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
3rd Apr 2018, 11:47 AM
Vicky Kuo
Vicky Kuo - avatar
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
3rd Apr 2018, 11:56 AM
Emma
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.
3rd Apr 2018, 5:54 PM
Manuel Maier
Manuel Maier - avatar
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.
4th Apr 2018, 12:05 AM
Emma
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.
4th Apr 2018, 9:15 PM
Manuel Maier
Manuel Maier - avatar
- 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
3rd Apr 2018, 12:24 PM
Emma