Need extra insights on this problem


#1
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

I didn’t know for loops within for loops were even a thing. The modules before this didn’t even go over this.

Why do we initialize with an empty string t? How does this line of code take vowels out?
if c==i:
c=""

It’s just an empty string.


#2

Maybe insert print statements and run your code here:

http://www.pythontutor.com/visualize.html#mode=edit

so the problem is run in steps? That might help

actually its a bit more complicated then that. I am not fan of this solution, its not very elegant.

lets take a two letter word we want to censor:

censor("me")

so for c in text will loop over "me", so the first iteration of the loop c will contain "m"

then we are going to compare "m" (c variable) with each vowel, by using another loop ( for i in "ieaouIEAOU"). Given the if condition will never evaluate to true, the else clause will run each iteration, re-assigning c to itself (which contained "m" value). Then after the inner loop, c variable ("m" value) is added to t (which will contain the anti-vowel string)

then we have the second iteration of the outer loop, so c will now contain "e" value. Now the if condition will evaluate to true, so c becomes an empty string and no longer contain "e"

now for the remaining iteration of the inner loop, it will just endlessly assign the empty string to c variable over and over again.

then after the inner loop is finished, c is an empty string, so an empty string is added to t.


#3

That was very helpful. Why do you consider this to be less elegant?


#4

i had to go through the code to understand how it worked, sometimes that is inevitable, but it shouldn’t be for this problem. There should be easier to read and cleaner solution.

the endless re-assignment of c variable and unnecessary loop iterations.

poor variable naming.

i think that are the most problematic issues with this solution.

How i would write the solution:

def anti_vowel(text):
    result = []
    for character in text:
        if character not in "aeiouAEIOU":
            result.append(character)
    
    return "".join(result)

print anti_vowel("hello world")

so much cleaner and easier to read


#5

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