[Solved] def anti_vowel – codecademy (python)

I am a bit stuck on creating the anti_vowel definition:

Define a function called anti_vowel that takes one string, text, as input and returns the text with all of the vowels removed

This is my attempt:

def anti_vowel(text):
    vowels=["a","A","e","E","i","I","o","O","u","U"]
    text_input=[""]
    for char in text:
        text_input.append(char)
    av = [char for char in text_input if char not in vowels]
    return av

My code returns the input as separate characters.

This is the error I get:

Oops, try again. Your function fails on anti_vowel("Hey look Words!"). It returns "['', 'H', 'y', ' ', 'l', 'k', ' ', 'W', 'r', 'd', 's', '!']" when it should return "Hy lk Wrds!". 

Could someone please point me in the right direction?

Enquirer: DJM91

||

Solution #1:

Consider:

>>> tgt='This is some text with vowels'
>>> vowels='aeiou'
>>> ''.join(e for e in tgt if e.lower() not in vowels)
'Ths s sm txt wth vwls'

Or, as pointed out in comments, using an actual list comprehension inside join is better:

>>> ''.join([e for e in tgt if e.lower() not in vowels])
'Ths s sm txt wth vwls'
Respondent: dawg

Solution #2:

return ''.join(av)

will make it back into a string from a list.

Respondent: Amadan

Solution #3:

You’re returning the list. Using join function you can convert the list to corresponding string.

Try:

return ''.join(av)

instead of return av

Respondent: Pankaj Sharma

Solution #4:

You’re looking for str.join which takes an iterable (like a list) as an argument and returns the string formed by using the object as a separator between each element of that iterable. For example:

lst = ['a','b','c','d','e','f','g']

''.join(lst) # 'abcdefg'
'/'.join(lst) # 'a/b/c/d/e/f/g'
'a'.join(lst # 'aabacadaeafag' etc etc...

Note that there are better ways to implement your function. str.translate(use THIS str.translate in Python2, which iirc is what Codecademy uses for their interpreter, it’s changed between versions) is BORN to delete characters from strings.

# Python3
def hate_vowels_py3(instring):
    transmap = str.maketrans('', '', 'aeiouAEIOU')
    outstring = instring.translate(transmap)
    return outstring

# Python2
def hate_vowels_py2(instring):
    outstring = instring.translate(None, 'aeiouAEIOU')
    return outstring

And using your method, there’s even an incremental improvement to be made. Any time you both

  • Don’t need to keep something in order and
  • Don’t need to have more than one of something

You should strongly consider using a set instead of a list. The set takes slightly longer to build for the first time, but lookups are MUCH faster. Remember that if you unroll that list comp you have:

# example string "Hello world!"

chars_to_delete = ["a","e","i","o","u","A","E","I","O","U"]
string = "Hello world!"
output_list = []
char = "H"
can_append_to_list = True
if char == "a": can_append_to_list = False
if char == "e": can_append_to_list = False
if char == "i": can_append_to_list = False
if char == "o": can_append_to_list = False
if char == "u": can_append_to_list = False
if char == "A": can_append_to_list = False
if char == "E": can_append_to_list = False
if char == "I": can_append_to_list = False
if char == "O": can_append_to_list = False
if char == "U": can_append_to_list = False # ten lookups to this list
if can_append_to_list: output_list.append(char)
char = "e"
can_append_to_list = True
# begin again..........

As you can see that’s a LOT of lookups to that list. Instead use a set, whose lookup time is BLINDINGLY fast. Either use the literal declaration:

vowels = {'a','e','i','o','u','A','E','I','O','U'} # looks like a dict with only keys
# (also IS a dict with no keys, but shhh that's an implementation detail)

or you can create one from any iterable by calling set() with the iter as an argument

vowels = set('aeiouAEIOU')
Respondent: Adam Smith

Solution #5:

This is my solution:

def anti_vowel(text):
    vowels = 'aeiouAEIOU'
    textlist = []
    for char in text:
        if char in vowels:
            continue
        else: 
            textlist.append(char)      
    return "".join(textlist)

Solution #6:

This is my solution:

 passage = '''We hold these truths to be self evident,
    that all men are created equal!'''
    def anti_vowel(text):
        vowels = ['a','e','i','o','u','A','E','I','O','U']
        text = list(text)
        i = 0 
        while i < len(text):
            if text[i] in vowels:
                del(text[i])
                print(i)
                i = i
            else:
                print(text[i])
                i += 1
                s = ''.join(text)
        return s

    print(anti_vowel(passage))
Respondent: RD Islam Nasim

Solution #7:

another simple way to solve this problem…

def anti_vowel (text):
   new_text=""
   for char in text:
     if char not in "aeiouAEIOU":
       new_text+=char
   return new_text
Respondent: Bar Amrani

Solution #8:

def anti_vowel(text):
    vowels = "aeiouAEIOU"
    for x in vowels:
        text = text.replace(x, "")
    return text
Respondent: Rahul

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.