7. reverse


#1



I have trouble understanding line 5 and 6.


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


#2

What you're doing is you're setting count to the length of text. Then you're going DOWN instead of UP thus making you start at the last character, and end at the first. Each time you do this (until you're at the first letter) you're adding the character to rev.


#3

impressive that people have no idea how the code worked they wrote.

@bhargav.py do you understand it now? If not, could you be a bit more specific what you don't understand. We are here to help you, the best way we can do this is if you are specific in what you don't understand


#4

Hi stetim,

First of all, thanks for no response in accordance to the post( Just kidding ). But, after looking through your profile it seems like you have a helped too many people. Through which, comes to my notice about this one post where you exactly helped a guy understanding the documentation. Can you help me how to do that? I'll glad if you could help.

Thanks in advance.


#5

not any change you have the url of this post?

Did tekkie's explanation help? What is it you do not understand? You could start by adding a function call:

def reverse(text):
    rev = ''
    count = len(text)
    while count > 0:
        rev += text[count - 1]
        count -= 1
    return rev
print reverse("How does reverse work?")

then we can add print statements, so we can see what the code is doing:

def reverse(text):
    rev = ''
    count = len(text)
    while count > 0:
        print "count: {:d} reversed string: {}".format(count,rev)
        rev += text[count - 1]
        count -= 1
    return rev
print reverse("How does reverse work?")

i print count and reverse, so you can see what count is, and what is in the reversed string.


#6

Is it necessary to use While? I made mine with FOR loop:

def reverse(text):
    length = len(text)
    word = ""
    for i in range(1, length+1): word += text[-i]
        return word

reverse("abcde")

#7

no, it is not, why should it be? There are multiply ways to solve a problem.


#8

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