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

This is the code snippet. I know it reverses the string "text" but can't seem to understand how it does so.

9
  • Which part is it, you can't understand? Commented Jun 10, 2013 at 15:47
  • 5
    It does so very inefficiently :( Commented Jun 10, 2013 at 15:47
  • 1
    It basically takes characters off of the end of text and places them at the end of final_string. But why don't you throw some prints in there and verify this yourself? Commented Jun 10, 2013 at 15:50
  • 1
    @JoeFrambach indeed, it looks like something directly mapped from c to python Commented Jun 10, 2013 at 15:51
  • 1
    This text = text[0:len(text)-1] -> reduces the text everytime by 1 less character from the right. i.e. if text = "Prakhar", text = text[0:len(text)-1]makes it Prakha. The next iteration will make it Prakh. Commented Jun 10, 2013 at 15:53

4 Answers 4

3
def reverse(text):
    final_string = "" 
    count = len(text) # sets the counter variable to the length of the string variable
    while count > 0: # starts a loop as long as our counter is higher than 0
        final_string += text[len(text)-1] #copies the last letter from text to final string
        text = text[0:len(text)-1] #removes the last letter from text
        count -= 1 #decrements the counter so we step backwards towards 0
    return final_string
Sign up to request clarification or add additional context in comments.

Comments

3

final_string += text[len(text)-1 gets the last character of text and adds it to the end of final_string.

text = text[0:len(text)-1] removes the last character of text; basically it shortens text by the character that was just added to final_string.

count -= 1 counts down to zero. When zero is reached text is 0-length and final_string has all of the characters in text added to it.

Comments

1

It repeatedly adds the last character from text to final_text and then shortens text until it should have no more characters.

Comments

0

It takes an answer string, finds the length of original text and places it in a variable count. It then uses this variable to places the string from reverse to front one character at a time while deleting the characters from the original string.

Much better solution would be

reverse_text = text[::-1]

That is all that is needed for reversing a string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.