7. Reverse


#1

Hello,

I have a question on this exercise:


https://www.codecademy.com/courses/python-intermediate-en-rCQKw/1/1?curriculum_id=4f89dab3d788890003000096


I feel I'm very close. I looked at some other solutions and maybe those are better than mine but I want to see how I can fix my code to format correctly.


The text is "Python!" and I am getting the reverse of this to print out, but the problem is that it's printing one letter per line, instead of printing one letter after the other.

I could start completely over using someone else's solution (I looked at some solutions but they look completely different than mine). Is there a way to fix how I started writing this so it prints on one line without completely rewriting all the code?

Here is my code:

def reverse(text):
    length = len(text)
    for i in text:
        print text[length-1]
        length = length -1
        
text = "Python!"
reverse(text)


This is the current output when I run my code:

!
n
o
h
t
y
P
None



Thanks


#2

We need to return the reversed string, so don't print. Append it to a list then return the joined list with and empty string separator.


#3

I would suggest putting the reversed text into a string, and printing it.


#4

We are given the advice of not mutating a string. For this reason, we build a temporary list and then join it in the return statement. The return value can be printed outside of the function.

temp = []

     temp.append( ... )


return ''.join(temp)

and then,

print reverse("Python!")

#5

Oh, didn't read the instructions of the exercise, I just gave my suggestion based from what I saw in the code. Sorry about that.


#6

Thanks guys, I'm getting closer but stuck at properly returning.

I can get it to print backwards with this code:

backwards = []

def reverse(text):
    length = len(text)
    for i in text:
        backwards.append(text[length-1])
        length = length -1

text = "Python!"

reverse(text)
answer = ("".join(str(x) for x in backwards))
print answer

but the answer wants this returned not printed. I can't use the return outside the function, and when I use it inside the function I get duplicate text:

backwards = []

def reverse(text):
    length = len(text)
    for i in text:
        backwards.append(text[length-1])
        length = length -1
    return ("".join(str(x) for x in backwards))    
    
text = "Python!"

reverse(text)

the above results in:

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

I've been messing around but I can't figure out how to use the return since my function is a loop...


#7

Declare this empty list inside the function so it starts fresh with every call.

return ''.join(backwards)

#8

No problem. I don't know where I first read this advice, but I don't think it was in the lesson. Just passing it along as a general rule of thumb. Didn't mean to snub your reply.


#9

Thank you that worked!

Final code I've used in case it helps anyone else (I'm sure it can be written better), but:

def reverse(text):
    backwards = []
    length = len(text)
    for i in text:
        backwards.append(text[length-1])
        length = length -1
    return ("".join(str(x) for x in backwards))    
    
text = "Python!"

reverse(text)

#10

Your code seems to be written well in my opinion (I'm not that experienced myself). The other option was not to append but to create a temp string, holding one letter at a time, and add each of them in reverse into a new returned string.

def reverse(text) :
length = len(text)
backwards_string = ""
for char in text :
temp = text[length - 1]
length = length - 1
backwards_string += temp
return backwards_string

reverse("Python!")


#11

Thanks for sharing your method! :slight_smile:


#12

@pnewcom
Strings are immutable though, so when you say "add to the end" what is really happening is the whole thing is created anew, with the extra letters included at the end. That turns out really inefficient for large strings. A list doesn't have this problem as it can add to what's already there.

@codelearner10721
Without trying to change the overall concept, I'd want to change:

for i in text:
You're not using i, (and it isn't an index, so the name is misleading) so you should name it _ instead to show that you don't intend to use it (for the benefit of the reader, just a different name)
But better yet would be to iterate through the indexes that you intend to use, you can create those with the range function. This means you can remove two other lines and make the append-line simpler.

return ("".join(str(x) for x in backwards))
Each x is already a string, no need to convert it, and since you don't need to convert it, there's also no need for the generator expression as it's just iterating to provide an iterable (no effect)
When you already have a function to apply to each element, map would be a better fit than the generator expression (which we wouldn't use anyway): map(str, backwards)

length = length -1
either length-1 or length - 1, the former makes sense because it can be considered a single value instead of an operation, but usually the spaces are only taken out in function calls so I'd go with the latter here.

Also, if you're using the range function to produce indexes, and you're already using generator expressions, then you could create a one-liner out of that. (In other words, cleaning up your code without changing its concept results in a one-liner)


#13

Thanks for informing me. :slight_smile: And no harm done.

Thanks,
Tanini


#14

Thank you for sharing your code. I am still struggling to understand some bits of the code:

        temp = text[length - 1]
        length = length - 1

can any one explain this part please.!
Thank you in advance.


#15

In the context of the code I posted earlier; I stored the last variable out of the last index in temp and deincremented length in order to go backwards in the list. I originally tried to write that code as such,

temp = text[length - 1]
length -= 1

but I had an error when i deincremented, which was weird, so i spelled it out for the compiler.


#16

I used a contencating comma. So after your print statement (print text[length - 1]) put a comma. It should read :

print text[length - 1],

and will print
! n o h t y P


#17

It's not supposed to print, but return a reversed string.


#18

Oops! Sorry about that. Thanks for pointing it out! :slight_smile:


#19

def reverse(text):
    reversed = []
    a = len(text)
    for i in range(a):
        letter = text[a-1]
        reversed.append(letter)
        a = a - 1
    return ''.join(reversed)

#20