Reverse


#1

Help!
I'm new to coding and I'm having a hard time with this exercise. The program I wrote is taking to long to run and codeacademy is suggesting to me that I wrote an infinet loop, but I can't figure out why.

def anti_vowel(text):
    
    your_word = raw_input ("Write a word. Any word: ")
    word = ""
    length = len(text)
    
    while length > 0:
        
        word += text[(length - 1) ]
        lenght = length - 1
    
    return word

#2

exactly which exercise are you at? The title suggest 7. reverse, but you called your function anti_vowel, bit weird. Can you confirm which exercise you are at?


#3

you did indeed write an infinity loop, look close at this line:

lenght = length - 1

you misspelled length, causing the infinity loop (since the wrong variable gets updated)


#4

Mine just won't work

def reverse(text):
   text = ""
   l = len(text)
   while l > 0:
       text += text[(l-1)]
       l = l - 1
   return text

#5

If I am not mistaken your first step is to override your variable text telling your computer that text is an empty string now. Then you check if the length of your text string is bigger than zero ( which it obviously isn't anymore, because you defined it to be zero)
After that you try to assign text a new value by telling your computer to add nothing[(length of nothing) - 1] == nothing += nothing[(0-1)] == nothing += nothing[-1]
Let's imagine nothing is something. In this case I think it would look like this: something += something[(len(sth))-1]
If your string would actually be "sth" then len(sth) would be 3 which leads to something += something[2].
The third position in "sth" is an "h" you remember -> Arrays always start counting from 0
So in the end you add "h" to "sth" which makes it "sthh". After that you reduce your l value until it is 0 which leads to text = "sthhts"
But in your case it just returns "" because text= "" which has a length of 0 which lets python skip your while loop.
PLEASE ANYBODY…IF I'M MISTAKEN IN ANY WAY, LET ME KNOW!
Hope reading this might help you to understand better why it doesn't work and can help you to reconsider and find a way to make it work :slight_smile:


#6

Hey fofolete,
I was wondering about your variable your_word which is supposed to get assigned by the user.
I'm confused about the fact that you never seem to use it again, so whats the point of having it?
Using your function later on in a bigger program in this way would make a lot more sense to me:

text = raw_input ("Write a word. Any word: ")

print anti_vowel(text)

for example…
but maybe I missed sth :slight_smile:


#7

You're right. I changed it to what you suggested! Thanks :wink:


#8

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