Anti_vowel - please explain codeacademy's default answer


#1

When Codecademy says’s “Get Code” this is what it returns.

Can someone please break this code down for me line by line!

def anti_vowel(text):
t="“
for c in text:
for i in “ieaouIEAOU”:
if c==i:
c=”"
else:
c=c
t=t+c
return t


#3

The code is an example of the most rudimentary, brute force approach.

  • Start with an a variable initialized to an empty string.
  • Set up a loop to iterate over the text, character by character.
  • Iterate over the vowel list and compare each one to the current character.
  • If there is a match, then cache an empty string in the temporary variable.
  • If no match then cache the current character in the temporary variable.
  • Replace the running string value with the concatenation of the old string and the current temporary variable value.
  • When the outer loop is complete, return the stored string value.

We call this a brute force approach because it iterates the maximum number of times, every time, and never deviates from that algorithm. More to the point, when c is 'a' it still iterates over the entire vowel list making unnecessary comparisons.

There is no fault in this approach since it is like starting with a fundamental model that has no abstracts. We can draw it out with pencil and paper. It doesn’t get simpler than this. A great place to launch from.

Now it is our task to play with the code and see where we can improve its efficiency (perhaps) and readability (again, perhaps). We can use it as a springboard to alternate approaches for the sheer experience of leveraging code from different angles.


#4
def anti_vowel(text): #creates the function that takes an argument called ext
t="" #creates and empty list called t
for c in text: #for every character (one by one) in text do the following (if text is a string)
   for i in “ieaouIEAOU”: #a loop within a loop for every character in the string “ieaouIEAOU” do the following
   if c==i: #so if the character from your input is equal to a character in“ieaouIEAOU” 
       c=""# that character will now be a ""(empty string)
   else: # if the character is not a vowel (not in “ieaouIEAOU”)
       c=c # that character is stored in a temporary variable called c
       t=t+c #and our empty string called t is now changed to add the character that is not a vowel.
   return t # returns our string called t which now should include all characters from our input(text) that aren't vowels

#5

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