Issue
I am trying to rewrite a formula by counting how many parenthesis are there in a formula.Starting with s=0 and increase s whenever finding a "(" and decrease it when finding a ")" but leaving "(" and ")" corresponding to their original indices in the new string. This sounds very simple, and probably it should be so, but I am failing to find the solution . This is what I coded:
def parenthesis(text):
s=0
result=""
for character in text :
if character=="(":
s+= 1
if s>0 :
result+= str(s)
if s==0 :
result+=str(0)
elif character==")":
s-=1
return result
For this input:
print parenthesis("(asss)+(aa(12))")
I get
111111011122221
And I am having problem in assigning "(" and ")" to the the numbers that correspond to the original indices.
like:
(1111)0(11(22))
I was trying for many times now to implement something similar to this:
for i in range(len(result)):
if result[i-1]<result[i]:
result[i] = "("
if result[i-1]>result[i]:
result[i] = ")"
But of course this is a string assignment and it won't work like this, so my question is how can I go around this or if there is a simpler way am all ears, grateful for any help.
Solution
You need to add the parentheses to the result after identifying them. You just add to the count.
Looks like you're looking for something like this:
def parenthesis(text):
count = 0
result = ""
for character in text:
if character == "(":
count += 1
result += "("
elif character == ")":
count -= 1
result += ")"
else:
result += str(count)
return result
print parenthesis("(asss)+(aa(12))")
This outputs:
(1111)0(11(22))
Answered By - pushkin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.