Reverse HELP ?! So close, can't figure it out


#1
  1. reverse

Error i keep running into: Your function fails on reverse(“Python!”). It returns “[‘c’, ‘a’, ‘b’, ‘c’, ‘!’, ‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’, ‘!’]” when it should return “!nohtyP”.

My code returns all of the input but only iterates through a part of input

I do not understand why it is only going through a part of it.
Here is my code:


m = []
i = int()
def reverse(text):
  for i in range(-1,len(text)):
    m.append(text[-i])
    i = i - 1
  return m
 



#2

you declare m outside the list, so calling the function multiply times:

m = []
i = int()
def reverse(text):
  for i in range(-1,len(text)):
    m.append(text[-i])
    i = i - 1
  return m
print reverse("abcd")
print reverse("python!")

will cause m to accumulate data, which shouldn’t happen


#3

Sorry, I’m stuck on this exercise.
Please, could someone explain the solution ?
Why the variable i is negative in m.append(text[-i]) ?


#4

Explaining the solution takes away 90% of the purpose of the exercise

well, we can use negative indexes to access the list from the right hand side, then appending to list cause the string to reverse


#5

negative indexes were not explained , but thanks anyway:slightly_smiling_face:


#6

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