Reverse


#1

can anyone please help me with my code
def reverse(text):
i = len(text)-1
while i >= 0:
return text[i]
i = i - 1
print reverse('python!')

it displays this error
Oops, try again. Your function fails on reverse("Python!"). It returns "None" when it should return "!nohtyP".


#2

That function of yours dosn't look like it would return None for 'Python!', are you sure you posted the right code? In any case, the indentation is missing.

The return statement exits the function, so you can't return more than once, because the function is no longer being executed.

A function that does not explicitly return anything will return the value None, so perhaps you forgot to return in the version of your code that we can't see.


#3

thank you @ionatan

I corrected my code then also it failed to work

here's my code

def reverse(text):
    j = []
    i = len(text)-1
    while i >= 0:
        j.append(text[i])
        i = i-1
    return j
print " ".join(reverse('abcd'))

#4

In what way does it fail? We have no idea what to look for without that information! It's also essential for you to figure it out on your own!

Consider what value type your function is supposed to return, and what yours returns

And that's much better, now we can actually read and run the code. If we have to modify it to run it, then we might not end up with the same thing as you have, right? Not to mention it's not exactly inviting.


#5

Just want to note that you've avoided some pitfalls in your code.

1) You do not "append" to strings. This isn't possible anyways, because strings are immutable, so "appending" to strings really means to re-build the entire thing, this turns out to be very expensive.
2) You loop backwards and append to a list. You could also have looped forwards and have inserted at the front of the list, but this is also very expensive, because to do that, all the already existing elements have to move one step to make room at the front. But appending at the end of the list takes constant time (doesn't matter how big the list already is)

As probably mentioned in the exercise instructions, for the purpose of the exercise it's cheating to use slicing:

def reverse(seq):
    """ redundant function really, just use slicing """
    return seq[::-1]

But this is exactly how one would normally do it and is going to be faster than anything you could possibly implement yourself since the built-in stuff plays by other rules than your own code. (It's written in C)

Slicing might look a little intimidating, but its three parameters matches that of the range function: start, exclusive stop, step. And leaving blank means to use default values. [::-1] thus means negative 1 step (backwards) and it'll default to starting at the end and stopping after the beginning.


#6

thankyou @ionatan

finally I solved

here's my code

def reverse(text):
    j = []
    k = ""
    i = len(text)-1
    while i >= 0:
        j.append(text[i])
        i = i - 1
    for l in j:
        k = k + l
    return k
print reverse("superman")

#7

Can someone tell me how is it working. I don't get how having k = "" would make it work. I guess I don't get which exact part causes the word to reverse.


#8

Hey guys, I'm also having a problem with this exercise, and am getting the same error "Your function fails on reverse("Python!"). It returns "None" when it should return "!nohtyP" - I have no idea why my code is failing.

Here is the code:

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

I chose to not go the while/for route that @pkarthicbiz did as I found it to be a bit lengthy and unnecessary - but also I may just be bad and thats the only way to go:/ Any help would be nice:)


#9

yo

after append the reversed character in j the whole list looks like

['!', 'n', 'o', 'h', 't', 'y', 'p']

we declared k as null
using L we loop the character in j[] and add it in k
for eg:
A + B = AB
same !+N+O+H+T+Y+P = !NOHTYP


#10

@pkarthicbz, It can be done a bit easier I believe, this is my code:

def reverse(text):
    result = []
    i = len(text)-1
    while i >= 0:
        result.append(text[i])
        i = i-1
    return "".join(result)

Same method we used for the battleship project to clean up what we return.


#11

@mastermblack, I tried your code also but you can't just count down with a for loop, you need to go to a negative number as in range(start, end, stepsize). Found it at this source: https://docs.python.org/2/library/functions.html#range

Hope it helps.

>    def reverse(text):
>         result= "" 
>         for char in range(-1,-len(text)-1,-1):
>             result = result + text[char]
>         return result

#12

why do you need the "-1" in "i = len(text)-1"


#13

Thanks @jmverboom solved my problem:)


#14

Say we are pulling from the string "cat". len(cat) = 3, but we want to use the indices to access the final character first. We want to return the character "t", then "a", then "c". To do this we will need to tell the computer that i initially is equal to the final index which in this case is cat[2] = t, because the first index value is always 0. Since the final index value is equal to 2 we must subtract one from the length of the string. I hope that helps.


#15

I have tried this; and it seems to be working. Can some expert tell me if this is the right way or I just did a manipulation like a novice. Also, how to make it better?

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

#16

@susenj I don't know how to make it better, but it works perfectly


#17

Use a list while putting things in place, strings are not mutable and you're making a bunch of copies. Extremely slow for large strings.

Except for that there's a hack in CPython, it cheats a bit and does the right thing. But your code says to do the wrong thing, which is bad.


#18

Hello!
Here is my solution with a while loop. Feel free to test it.
All the best.

bb

def reverse(text):
    c = 0
    rev_txt = ""
    while c < len(text):
        rev_txt += text[-1-c]
        c += 1
    return rev_txt

#19

@bostjanb
You might want to test it yourself, that will not reverse anything.


#20

Hello iontan!
Thank you for your feedback. You were right, there was a mistake.
I fixed it and should work now.

cheers.