7. reverse


#1

Hey guys, this code gives me this error message: Oops, try again. Your function fails on reverse("Python!"). It returns "[]" when it should return "!nohtyP".
However, it prints cba!nohtyP.
So, very close but I have three questions:
1. Why does it say that it returns an empty list?
2. Why does it not matter if in the while statement c>any number but in my opinion it should be larger than -1 regarding the index?
3. Why does it print cba in front of my answer?

def reverse(text):
    total=[]
    text=str(text)
    c=(len(text)-1)
    while c>-1:
        total.append(text[c])
        c-=1
    return total
print ''.join(total)

Help is much appreciated


#2

i get the following error when running your code:

Traceback (most recent call last):
File "python", line 9, in
NameError: name 'total' is not defined

the join should happen inside the function.


#3

I don't get this error somehow.
What do you mean the join should happen inside the function? I tried to do that like saving the join statement as a new variable inside the function but it did not work neither...


#4

can i see the version of your code where you do the join inside your function?


#5

def reverse(text):
    total=[]
    text=str(text)
    c=(len(text)-1)
    while c>6:
        total.append(text[c])
        c-=1
    x=''.join(total)
    return total
print x

I have the feeling that this is not at all what you meant :smile:


#6

why did you change your loop syntax? that was fine

lets go back here:

def reverse(text):
    total=[]
    text=str(text)
    c=(len(text)-1)
    while c>-1:
        total.append(text[c])
        c-=1
    return total

if you run this code, you will get an error:

Your function fails on reverse("Python!"). It returns "['!', 'n', 'o', 'h', 't', 'y', 'P']" when it should return "!nohtyP".

all you need to do, before returning total is to convert the list into a string. and then return the string


#7

Thank you very much!
I got it...
Sometimes one doesn't see the wood for trees...


#8

this was my solution:

def reverse(text):
    ans = ''
    minus = -1
    while len(ans) < len(text):
        ans += text[minus]
        minus += -1
    return ans

what do you guys think?


#9

strings are immutable in python, so here:

ans += text[minus]

a copy of the string is made, containing the combined result. Not very efficient. For the rest it is a good solution


#10

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