7.Reverse


#1

https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/reverse?action=lesson_resume

This is my code:

def reverse(text):
new_text = ""
for x in range(len(text), -1, -1):
new_text += x
return new_text

print reverse(“abcd”)


I don’t understand why is not working…

This is the error I get:

File “python”, line 7, in
File “python”, line 4, in reverse
TypeError: cannot concatenate ‘str’ and ‘int’ objects


#2

range() will give you a range of integers. You’ve created a range of 4 to 0, stepping backwards from 4 until it gets to 0.

range(len(text), -1, -1) # //-> [4, 3, 2, 1, 0]

In the for loop, you are looping through each of the numbers and storing that number in the variable x.

  • So on the first loop, x = 4.
  • The next loop, it equals x = 3.
  • And so on until it gets through the range of numbers you created, i.e. from 4 down to 0.

You want to use that x as an index to get the associated character in the incoming string. Huh?

abcd breaks down to:

  • Index 0 = a
  • Index 1 = b
  • Index 2 = c
  • Index 3 = d

Think about how to do get the character out of the string. How can you use that x as an index for text?

Deeper Explanation of What Your Code is Doing

Just in case you wanted to know what you current code is doing, let’s walk through it.

To see the range of numbers you are generating, put this into your code:

def reverse(text):
  new_text = ""

  # print the range that is being generated
  # the result is: [4, 3, 2, 1, 0]
  print range(len(text), -1, -1)

  for x in range(len(text), -1, -1):
      new_text += x 
  return new_text

Then the loop iterates through that set of numbers starting with 4 and going to 0.

Now look at this line of code:

new_text += x 

What’s it doing? On the first loop, x = 4. You are attempting to concatenate an integer of 4 to the string in new_text.

Think about this. Will that reverse the incoming abcd? Not the way you have it now, as it’s just concatenating: the integers together. Do you see that?

Here let me help you to visualize it:

def reverse(text):
  new_text = ""

  # print the range that is being generated
  # the result is: [4, 3, 2, 1, 0]
  print range(len(text), -1, -1)

  for x in range(len(text), -1, -1):
      # convert the integer into a string using str()
      new_text += str(x)

  return new_text

print reverse('abcd') # //-> "43210"

The result of running your code gives you a string of integers: '43210'.


#3

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