Reverse


#1



I got this code to pass the reverse exercise, but not sure if this is good practice

def reverse(text):
    t = ""
    for c in text:
        t = c+t    
    return t


#2

I did the same , short and simple :smiley:


#3

can u explain how this code works?


#4

I used this :smiley:

def reverse(str):
    kappa=""
    for symbol in str:
        kappa=symbol+kappa
return kappa

#5

Example:
reverse(cherry)
The loop goes through 6 iterations (6 letters in cherry)
1st:
Start:
c = 'c'
t = ''
Then:
t = 'c' + ''
End:
t = 'c'

2nd:
Start:
c = 'h'
t = 'c'
Then:
t = 'h' + 'c'
End:
t = 'hc'

3rd:
Start:
c = 'e'
t = 'hc'
Then:
t = 'e' + 'hc'
End:
t = 'ehc'

4th:
Start:
c = 'r'
t = 'ehc'
Then:
t = 'r' + 'ehc'
End:
t = 'rehc'

5th:
Start:
c = 'r'
t = 'rehc'
Then:
t = 'r' + 'rehc'
End:
t = 'rrehc'

6th:
Start:
c = 'y'
t = 'rrehc'
Then:
t = 'y' + 'rrehc'
End:
t = 'yrrehc'


#6

lol that's same as mine XD


#7

Very nice. I would have never thought of that.


#8

:grinning:Can you please tell me how this one works? it's really simple. i like it.:grinning:


#9

Please refer to entimaniac's explanation above :smile:


#10

I did the same, but mine's not working. I get an error message saying - Oops, try again. Your function fails on reverse("Python!"). It returns "!nohtyP " when it should return "!nohtyP".

This is my code -

def reverse(text):
a = " "
for i in text:
a = i + a
return a


#11

seems theres an extra white space, set a="", with no space between the double-quotes


#14

def reverse(text):
reverse = []
for i in range(len(text) - 1, 0 - 1, -1):
reverse.append(text[i])
print "".join(reverse)


#15

Clever solution - didn't even think of something similar to that :frowning:

Skirted on the edge a bit using .reverse for the list element (strictly, it was only the string method .reversed that we were not supposed to use... :slight_smile: )

def reverse(text):
    new = list(text)
    new.reverse()
    my_string = "".join(new)
    print my_string

#16

This is sort of what I was getting at as well but I couldn't get the syntax to work out quite right. Good to see someone else on the same page!

This ended up working though:
def reverse(text):
newtext = ""
i = len(text)-1
while i > -1:
newtext = newtext + text[i]
i -= 1
return newtext


#17

It took me a while, but i finally got it. Here's my code.

def reverse(text):
new_word = ''
for i in range(len(text) - 1, -1, -1):
new_word += str(text)[i]
return new_word


#18

it works if you make text=raw_input("enter something")


#19