Reverse


#1



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


I didn't get a message but I don't know what I have to change from here.
The code below keeps print out "", instead of reserved word.


def reverse(x):
    s = ""
    for n in range(len(x),0):
        s += x[n]
    return s

reverse("abcd")


#2

Hi @meigi,

The problem is due to the arguments that you passed to the range function in this for loop header ...

for n in range(len(x),0):

See the documentation for the range function.

Some things to consider regarding the range function are ...

  • The start value is inclusive.
  • The stop value is exclusive.
  • To proceed from a start value that is greater than the stop value, a negative step value needs to be included as the final argument.
  • The index of the final character in a string is 1 less than the number of characters in the string.

Taking all of that into account, your loop header should be changed to ...

    for n in range(len(x) - 1, -1, -1):

Also be aware that another way to approach this exercise is to use a list to accumulate the characters for the result, and then to use the str.join method. However, with appropriate arguments for the call to the range function, your strategy will work.


#3


- I created a variable to hold the letters of the string to be reversed
- strings are really lists of letters! so the string "Python!" is really a list of 7 letters.
- for..range(start, stop, skip) - which index to start the for loop; which index to stop (in this case, the first letter, or index 0), how many to skip (down 1, or -1, each time)
- I also printed the index, and what var1 looks like after each iteration - this really helps to visualize what the new string looks like until completion
- so var1 holds each letter GOING BACKWARDS from the original string's order. For example, 'abc' will turn to'bca'.
- then return the new string "var1"
- then call the reverse("your word")/


#4

Fixed that for you.

Why shouldn't this work? It makes more sense logically.

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

#5

Hi @jessetrue,

The range in this loop header is empty ...

for char in range(0, len(text), -1):

With a step of -1, there is no sequence from 0 to len(text).


#6

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