I have a function that takes in an argument, preferably a string, takes each value of the string and implements them as elements in a list. After that, it iterate's through the list and is supposed to delete/remove elements that are round brackets, so basically, these: (
)
. Here is the code:
def func(s):
n = 0
s = [i for i in s]
for i in s:
if s[n] == "(" or s[n] == ")":
del s[n]
else:
n = 1
continue
return s
print(func("ubib0_)IUBi(biub()()()9uibib()((U*H)9g)*(GB(uG(*UV(V79V*&^&87vyutgivugyrxerdtufcviO)()(()()()(0()90Y*(g780(&*^(UV(08U970u9yUV())))))))))"))
However, the function stops the iteration and ends/returns the list early (when some round brackets are still there).
I also went with another way, a way that works:
def func(s):
n = 0
s = [i for i in s]
s2 = [i for i in s if i != "(" and i != ")"]
return s2
print(func("ubib0_)IUBi(biub()()()9uibib()((U*H)9g)*(GB(uG(*UV(V79V*&^&87vyutgivugyrxerdtufcviO)()(()()()(0()90Y*(g780(&*^(UV(08U970u9yUV())))))))))"))
Why does this work while the other way doesn't? They like they'd output the same result. What am I doing wrong in the first example?
CodePudding user response:
Your concept is correct, in that you either delete the current item or increment n
.
Where you've gone wrong is that you're iterating over each letter which doesn't make sense given the above info. Changing for i in s
to while n < len(s)
will fix the problem.
A couple of things you may find useful:
list(s)
looks cleaner than[i for i in s]
i not in "()"
is another way to writei != "(" and i != ")"
CodePudding user response:
At the beginning when you're increasing n
, n
equals to i
. But when you meet a bracket, n
has the same value the next iteration, and i
increases. It happens every time s[n] == "(" or s[n] == ")"
and the difference between n
's and i
's values increases.
To work correctly you program needs to check every symbol in the list (string) for equality of either '('
or ')'
using s[n]
, but it doesn't happen because the iteration stops when i
achieves the end of the list and n
at that time is much less than i
and it hasn't achieved the end of the list yet and hasn't checked all symbols.