7/15 Reverse: Practice Makes Perfect


Can someone help me out with this please!
I think you'll be able to see what im trying to do.
1) Make the input a list
2) Identify how many letters are in the text
3) Loop it backwards into the reversed_letters empty variable
4) Join it back into a single string when x = 0


I also tried "reversed_letters.append(letters[x])"


def reverse(text):
letters = list(text)
reversed_letters = []
x = int(len(text))-1
while x > -1:
x -= 1
return ''.join(reversed_letters)

print reverse("abcd")

Here guys :smile:


I'm not sure if this is the correct way to do it, but it worked for me.

def reverse(text):
num = len(text) - 1
rev = []
for i in range(-1, num):
num -= 1


Check this solution:

def reverse(text):
rev = ''
count = len(text)
while count > 0:
rev += text[count - 1]
count -= 1
return rev


def reverse(text):
rev_text = []
text_len = len(text)
while text_len >0:
text_len -=1
end_text = ''.join(rev_text)
return end_text

Works fine


I got a weird response when attempting this. I was able to successfully pass the question, but when I call the function in the code it doesn't provide what should be the correct response. My code is:

def reverse(text):

# Find the number of indices in the string
num_of_characters = len(text) - 1

# Initialize x as an empty LIST
x = []

print text[num_of_characters]

while num_of_characters > -1:

    # Append the letters to the list 'x' from text

    # Lower the index to the next character
    num_of_characters -= 1

# Join all the values in the list as a new string    
end = ''.join(x)
return end


When I call reverse("Python!") it only returns ! in the console view, am I missing something? I passed the section but it still doesn't seem like the output is correct.


Remove print statement from function definition (just before while loop). Then call function with print: print reverse("Python!")


You are thinking way too complicated. Remember that you can view strings or access strings like lists. So here is another possible solution:

def reverse(text):
    # Our empty string for the reversed text
    reversed_text = ""
    # Note: Indices are starting with zero and the last number in ranges aren't included
    for i in range(len(text)):   
        reversed_text += text[len(text)-1-i]
    return reversed_text


well done 0xmoon. I think that is the simplest code. I did:

def reverse(text):
    b = ""
    for a in range(1,len(text)+1):
        c = len(text) - a
        b += text[c]
        a -= 1
    return b

text = "abcd"
print reverse(text)

def reverse(text):
    reversed = ""
    # range(start, stop, step)
    # start = len of string minus 1 (because initial index is 0)
    # stop = -1 (range don't include the stop value, and we want stop on 0)
    # step = -1 (reverse order on range function)
    for i in range(len(text) - 1, -1, -1):
        reversed += text[i]

    return reversed

i don't use list:D

      def reverse(x):
>         y = str(x)
>         z =len(y)
>         num = z-1
>         ynum = ""
>         for i in range(z):
>             ynum =  ynum +y[num]
>             num = num -1
>         return ynum


I will add my two cents!


def reverse(word):
    return ''.join([word[-(index + 1)] for index, letter in enumerate(word)])


This works too by populating the list backwards. Indexing each item in order to index 0:

def reverse(text):

	reversed_text = []

	for t in text:
		reversed_text.insert(0, t)
	print ''.join(reversed_text)


Hey 0xmoonstar love the solution, however where in the function where takes the string and reverses it's order?

def reverse(text):
    length = len(text)
    reversed_text = ""
    for index in range(length-1,-1,-1):
        reversed_text += text[index]
    return reversed_text


Hi Oxmoonstar,

Could you possibly explain that line by line / bit by bit?

Thanks a ton.


For pogs and gerald_sky I'll explain my code:

def reverse(text):
    # Our empty string for the reversed text
    reversed_text = ""
    # Note: Indices are starting with zero and the last number in ranges aren't included
    for i in range(len(text)):   
        reversed_text += text[len(text)-1-i]
    return reversed_text

Let's start to invoke the function with a real input:


What is happening in that function if the input is "cat"?

First the variable text will be assigned to the String "cat" (text = "cat").
len(text) returns the length of the input string, which here is "cat" and therefore has a length of 3.

The condition for the loop cycle is that variable i has to be in range(len(text)), in our case it's range(3), because like said before the length of the word "cat" is 3.

for i in range(len(text)):

We know that range(3) generates the list [0,1,2]. The loop will iterate / cycle over the list [0,1,2] (which is equal to range(3)) till i takes a value which isn't in range (here it is i = [] which isn't in the list [0,1,2], [] is the empty list):

After the last iteration (where i = 2) the for-loop will be cancelled and the the program flow will continue at the line outside the "for-loop zone" which is return reversed_text once the the given range is being achieved.

But why reversed_text += text[len(text)-1-i] ?

We know that strings can be accessed like lists. The String "cat" can be imagined as ["c","a","t"] precisely text = ["c","a","t"]. You can access the elements of a list by naming the index of the element e.g. for the first element like this: text[0]. But we want to reverse the input word which is "cat" to "tac".

The idea is to access the last element "t" append it to the empty list called reversed_text, access the 2nd last element which is "a", append it to reversed_text (which has the string "ta") and at last append the first element "c" (reversed_text = "cat"; equal to: reversed_text = text[2] + text[1] + text[0]).

Let's sum it up:

  • We know that the variable i will start with the first element of the range which is 0
  • The last element of a text can be accessed like this text[len(text)-1]
  • For text = "cat" we have to do text[len(text)-1-0] + text[len(text)-1-1] + text[len(text)-1-2]

Sorry for the formatting. I'll polish it later... Hope that I could help you guys a bit...


Thank you! For that explanation.
You are incredibly good at explaining Python.


It's a very simple and nice solution, mine is more complex. thanks a lot