Anti_Vowel (Can't remove the "o")?


#1



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


I'm getting the error "Oops, try again. Your function fails on anti_vowel("Hey look Words!"). It returns "Hy lk Words!" when it should return "Hy lk Wrds!".


As far as I can tell I've included "O" and "o" in my vowel list so I'm not sure why it's failing to remove the o's


def anti_vowel(text):
    vowels = ["A", "E", "I", "O", "U", "a", "e", "i", "o", "u"]
    list_text = list(text)
    for i in list_text:
        if i in vowels:
            list_text.remove(i)
    return "".join(list_text)


#2

It worked when I surrounded the list_text in my for loop by another list() function.

E.g. for i in list(list_text):

I have no idea why that made it work so if someone could shed some light that'd be awesome.

Thanks.


#3

Removing elements from a list causes the following elements to move, that's something you have to account for.
All that moving also makes re-moving very expensive, it's better to spend a constant amount of time on each character, regardless of how many there are in total.


#4

Hi. My code (below) is also not removing the "o" in "words". I'm sorry but I don't understand your explanation. I understand that removing elements from a list will move the elements, but not why that means the final "o" can not be removed. The concept in your explanation, to spend a constant amount of time on each character, makes sense to me, but how to execute this? by separating the aeiouAEIOU with or statements?
Sorry if this is a pain, thanks

def anti_vowel(text):
    text = list(text)
    for char in text:
        if char in "aeiouAEIOU":
            text.remove(char)
    return "".join(text)

#5

That condition already takes a constant amount of time (always at most 10 comparisons), it's fine as it is.

Removing from a list does not take constant time, that takes time relative to the size of the list. First the character has to be found, and then the remaining elements moved.

When an element is removed and at the same time the loop moves forward, you will skip one element.

So that's two reasons, each sufficient by itself to not remove elements.

Pull up pen and paper and write some letters down and then present a piece of text with no vowels remaining. Look at what you do to accomplish this. There's no reason your program shouldn't do the same thing, and also no reason why it would be more difficult to come up with the same idea for your code since it can do the same things as you can do with pen and paper..Aside from artistic stuff anyway


#6

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