String processing in Python(as a list) -
i need advice. need write program in python requests user string s
consisting of left , right brackets, instance (()))(()(
.
after this, program needs count number of left , number of right brackets of input string. example, string (()))(()
contains 4 right brackets , 4 left brackets. hint: introduce 2 counters initialized 0 in beginning. explore symbols of string in loop. current symbol increment left
counter 1
f symbol (
, otherwise, increment 1
right
counter.
then, need test whether string math-like.
let call string math-like if brackets occur in mathematical formula. instance, strings ()
, (())()
, (()())
math-like, while strings ))(())((
, ())(()
not. need write program prints "yes"
if input string math-like , "no"
otherwise. hint: in particular, each iteration of loop, need check values of left
, right
counters satisfy particular condition.
i beginner, confusing me write implementation of task or @ least imagine how should look.
i appreciate type of help, because need solve problem. thank in advance!
sounds me you're looking answer course exercise you. main point of such thing you work out. here's starter, rather "here, give teacher."
token parsing requires more; paying attention order of parenthesis. here's how run through string , @ have:
test1 = '(()))(()(' test2 = '(()))(()' def ptest(test): lefts = 0 rights = 0 balance = 0 c in test: if c == '(': balance += 1 lefts += 1 elif c == ')': balance -= 1 rights += 1 print 'testing "'+test+'"' print 'lefts='+str(lefts)+' rights='+str(rights) if balance == 0: print 'balanced, possibly math-like' else: print 'unbalanced, not math-like' ptest(test1) ptest(test2)
Comments
Post a Comment