Anti_vowel: leaving 1/3 "o"s behind?!?


#1



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


I know this isn't the prettiest way of passing this exercise, but here's the code I came up with for an anti_vowel function:


def anti_vowel(text):
    lst_text = list(text)
    for letter in lst_text:
        if letter == "A" or letter == "a":
            lst_text.remove(letter)
        elif letter == "E" or letter == "e":
            lst_text.remove(letter)
        elif letter == "I" or letter == "i":
            lst_text.remove(letter)  
        elif letter == "O" or letter == "o":
            lst_text.remove(letter)
        elif letter == "U" or letter == "u":
            lst_text.remove(letter)
        else:
            print letter, "is not a vowel, you may pass!"
    new_text = "".join(lst_text)
    return new_text
print anti_vowel("Hey look Words")

For some reason the o in words isn't getting removed from "Words" even though it is getting removed from the word "look" (twice?!). What am I doing wrong here? I feel like such a failure...


#2

the problem is that you remove from the same string as you are iterating over.

the problem with successive vowels (like oo in look), the second vowel gets skipped because of index shift


#3

Oh very interesting! Thanks again for the help @ stetim94. Back to the drawing board for me...


#4

you can see this nicely if you do the following:

def anti_vowel(text):
    lst_text = list(text)
    for letter in lst_text:
        print "".join(lst_text), letter
        if letter == "A" or letter == "a":
            lst_text.remove(letter)
        elif letter == "E" or letter == "e":
            lst_text.remove(letter)
        elif letter == "I" or letter == "i":
            lst_text.remove(letter)  
        elif letter == "O" or letter == "o":
            lst_text.remove(letter)
        elif letter == "U" or letter == "u":
            lst_text.remove(letter)
            
    new_text = "".join(lst_text)
    return new_text
print anti_vowel("Hey look Words")

you can see how the second o of look gets skipped, and then when o in words is found, how remove() remove the first o it can find (the one in look which was skipped)


#5

that's a great checking method; much better than my "you may pass" thing at the end. I'm still struggling with how to fight the index shift, is there a way? Or is using .remove going to mess me up everytime (in an iterative loop at least)?


#6

a piece of advice first: I wouldn't use the remove method at all

The two easiest solutions would be:

loop over text while removing from lst_text

loop over a reversed list


#7

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