Stucked in anti_vowel


#1



anti_vowel


on calling function with string "Hey look Words!" , it gives output "Hy lk Words!"
instead of "Hy lk Wrds!"
I am not getting why the o in "Words" not get removed...


def anti_vowel(text):
    #text=text.lower()
    l=list(text)
    print l
    vowel=['a','e','i','o','u','A','E','I','O','U']
    for char in l:
       # print char
        for vow in vowel:
            #print vow
            if vow==char:
                print char
                l.remove(char)
               # break
    print l           
    return "".join(l)    
    
print anti_vowel("Hey look Words!")


#2

the o in words doesn't gets removed because of index shift.

while it looks like the problem is in words, the problem is actually in look:

l   o   o   k
0   1   2   3

if you remove the o of index 1 everything shifts to the left (since a string can't have empty indexes), so the of o of index 2 shifts to index 1, and the k of index 3 shifts to index 2

in the mean time, the loop has continued from index 1 to index 2, which now contains k (the second o of look gets skipped because of the index shift as explained above)

why is the o in look removed then? Because when the o in words is encountered, .remove() will remove the first o it can find, which is in lok


#3

Thank you very much.
So now I change it to :
def anti_vowel(text):
#text=text.lower()
l=list(text)
print l
vowel=['a','e','i','o','u','A','E','I','O','U']
i=0
while i<(len(l)):
print i
print l[i]
for vow in vowel:
#print vow
if vow==l[i]:
print i
# print l[i]
del(l[i])
i=i-1
print i
# break
i=i+1
print l
return "".join(l)

print anti_vowel("Hey look Words!")

And this is working fine :slight_smile:


#4

good you made it work :slight_smile:

The is rather long, don't you think? Maybe you can optimize, or not use del at all? removal is not a really nice approach for this problem


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.