Home > Software engineering >  for loop is not iterating correctly
for loop is not iterating correctly

Time:11-18

I tried to iterate through this list and append the indexes of the parenthases, but it gave the wrong ones back.

Code:

t = "(= 2 (  4 5))"
a = []
for each in t:
        if (each == '(') or (each == ')'):
            a.append(t.index(each))
        else:
            pass
print(t)
print(a)

Result:

(= 2 (  4 5))
[0, 0, 11, 11]

It should be:

(= 2 (  4 5))
[0, 5, 11, 12]

CodePudding user response:

You can avoid making python search back through a list (You have t.index(each)) by using enumerate() to get the index directly:

t = "(= 2 (  4 5))"
a = []
for index,each in enumerate(t):
        if (each == '(') or (each == ')'):
            a.append(index)
        else:
            pass
print(t)
print(a)

Output as requested

CodePudding user response:

In the condition of 'if', there is a space between '==' and '('. you should delete it. Write " if (each =='(') or (each ==')') " instead of "if (each == '(') or (each == ')')".

  • Related