Reverse


#1

def reverse(text):
    result = ""
    length = int(len(text))
    text = str(text)
    for i in range(length):
        if length > 0:
            result = result + text[length-1,length]
            length -= 1
        else:
            return result

Oops, try again. Does your reverse function take exactly one argument (a string)? Your code threw a "string indices must be integers, not tuple" error.


#2

length = int(len(text))
no need to use int() for casting.

This line also have no use as you have not changed actual string.
text = str(text)

This line,In python we use colons to have part of string when we use [] operator.

text[length-1,length] you have used comma.

Final result returned after process is done ,directly but you have put it in else clause ,that would never happen .
hint*
No need of else actually because your function deals with non 0 length strings.


#4

Had to make like this to make it work:

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

#5

Just saw,Reason..
when length gets value of 0(after reducing)
then youre looping over empty list ,it means your loop will iterate 0 times and it will not able to enter the for loop and will never execute the else clause.


#6

for i in range(length):
        result = result + text[length-1:length]
        length -= 1

This part deals with non empty text and reverses it.
You can directly return the final reversed string ,indentation is important,as final result should not be inside the for loop but at the same level as for loop.

if length == 0:
            return result

If you want to check for empty strings too,This is not necessary if you do what I mentioned as by default you will return empty string (as you initiated it an empty string, as your for loop will never run and by default it ( result = "")will return an empty string)


#7

Finally I got it, thanks


#8

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