8.anti_vowel


#1


https://www.codecademy.com/courses/python-intermediate-en-rCQKw/1/2?curriculum_id=4f89dab3d788890003000096#

Oops, try again. Your function fails on anti_vowel("Hey look Words!"). It returns "Hy lok Wrds!" when it should return "Hy lk Wrds!".


Hello, here is my code for the anti_vowel function. I don't understand why it returns "Hy lok Wrds!" when it should return "Hy lk Wrds!" and moreover with look having two o's the code should work normally. I would like someone to explain me why this happens and also debug my code.


def anti_vowel(text):
    mylist = list(str(text))
    i =0
    while i < len(mylist):
        for c in "aeiouAEIOU":
            if mylist[i] == c:
                mylist.pop(i)
        i += 1
    total = ''.join(mylist)
    return total


Anti_vowel ---> but WHY !?!?
#2

This is a tricky one!

The problem you're having is coming from the fact that you're treating the list as if it's still the same length, but you're actually shortening the length of the list every time you find a vowel, and this makes the i index of the list inaccurate.

Let's walk through what would happen each time we go through the while loop below

while i < len(mylist):
        for c in "aeiouAEIOU":
            if mylist[i] == c:
                mylist.pop(i)
        i += 1

First time in the while loop

mylist[0] is "s"
mylist[1] is "o"
mylist[2] is "o"
mylist[3] is "n"

i = 0
is s a vowel => no
do nothing

Second time in the while loop

mylist[0] is "s"
mylist[1] is "o"
mylist[2] is "o"
mylist[3] is "n"

i = 1
is o a vowel => yes
remove it from the list

Third time in the while loop

mylist[0] is "s"
mylist[1] is "o"
mylist[2] is "n"

i = 2
is n a vowel => no
do nothing


Fourth time in the while loop

i = 3
len(mylist) is 3
end the while loop


The result is that we end up with "son" instead of "sn"

Hopefully this helps you find a solution that works!


#3

As @liamseanbrady said, here we're dealing with dynamic nature of list (length of list changes at every iteration).
So I'd suggest to not convert text into list but create an empty string and add all non-vowel letters.
:slight_smile:


#4

oh yeah. i forgot about the fact that after deleting the value the value of i should go down by one. Thankx i got it right >


#5

actually it is fine i got it
i forgot to decrease the value of i when the if condition is met as i am deleting a value


#6

Have you tried it without a list, one one loop, and with replace? If using replace you need to reassign 'text' instead of just creating a new variable to store the new text in.


#10

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