7 reverse


#1
def reverse (x):
word = []
length = len(x)-1
for i in range(-1, length) : 
    word.append(x[length])
    length -=1
return "".join(word)

print reverse("word")

I got this code from someone. One thing I still don't understand fully is that how come "for i in range(-1, length): start from -1 instead of 0?

Thanks


#2

because need to loop (length + 1) times
it also possible range(0, length +1)


#3

Let's set up with some values.

# let x = "123456789"
x = "123456789"
# len(x) == 9
length = len(x)-1  # 8

Now let's study length in relation to i...

 i   length   o
-1      8     0
 0      7     1
 1      6     2
 2      5     3
 3      4     4
 4      3     5
 5      2     6
 6      1     7
 7      0     8
 8     -1

The length is 9, and there are 9 iterations. From this we can conclude that since the length variable is reduced by one, the start value of the iterator needs to be shifted to the left by one. This ensures full iteration, without missing the first index.


#4

Thanks this helps a lot


#5

how is that "x[lenght]" works? i donĀ“t understand...


#6

With x representing a string, length is acting as the index, or string position.


#7

if i change the first line as,

      length=len(x)

and second line as,

      for i in range(0,length):

the code is showing some index error ..what is wriong with that logic..??