Partially correct code...Please point mistake


#1



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


It returns "Hy lk Words!" when it should return "Hy lk Wrds!" when input is "hey look Words!"
Also It returns "Hy Yu!" when it should return "Hy Y!" when input is "Hey You!"


vowels=['a', 'e', 'i', 'o', 'u']
def anti_vowel(text):
    alphabets=[]
    for i in text:
        alphabets.append(i)
   
    for x in alphabets:
        if x.lower() in vowels:
            alphabets.remove(x)
        
            
    return ''.join(alphabets)


#2

solving this problem with remove is rather difficult, because you get an index shift, in this case caused by the word look. lets say our string is just look:

l   o   o   k
0   1   2   3

a little overview of our string with the indexes. what is happening? when remove encounters the o at index 1 it gets removed, so far so good. But strings can't have empty indexes, so the o at index 2 will shift to index 1, while the for loop continues to index 2.

so the index shifts causes letters to be removed

You might think: hey, this is confusing, because the o in look is removed. True, but remove will remove the first instance it will find, but the problem is in the word look (or any word which has successive vowels)

It is much easier to append constants (if x.lower() not in vowels) to a new list then using remove. Hope this helps


#3

but as i mentioned, the two 'o's in look are being successfully removed. the problem is with 'o' of 'Words'


#4

Just tossing in a comment... Removing elements from a list that is currently being iterated is discouraged, mostly because it is so inefficient and logic heavy. We know it can be done so we won't out and out say, it cannot be done. It's just got a lot of overhead.

There are one of two ways that come to mind. Iterate from the right side toward the left, or work with a copy that changes while iterating over the original. The logic we need to do either already exists in this forum so do a little digging and see it you can find one. Let us know what you settle on.

The shortest approach is the one we're sort of dissuaded from using because it doesn't give us any practice, so is not a fair submission for this exercise. If one doesn't understand this, that's okay. It is not meant as a solution, only an example of a more direct approach at an advanced level.

>>> text = 'aAbBeEfFiInNoOpPuU'
>>> for x in 'aeiou': text = text.lower().replace(x, '')

>>> text
'bbffnnpp'
>>>

#5

i covered that:

it arrives at the o of words, is then told to remove the letter o, but remove() will remove the first instance it will find, which is the o of lok


#6

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