Talka
Talka

Reputation: 15

Reverse exercise (Python Codecademy course, part "Practice makes perfect" 15/15)

the task runs as follows: Define a function called reverse that takes a string textand returns that string in reverse.You may not use reversed or [::-1] to help you with this.

My code works all right but I want to understand one detail. Tks to all.

def reverse (text):
    result = ''
    for i in range (len(text)-1,-1,-1):
        result += text[i]
    return result

The point is that originally I wrote in the 3rd line for i in range (len(text)-1,0,-1):But the program returned '!nohty' instead of '!nohtyP'. So I changed to (len(text)-1,-1,-1) ant it's ok. BUT WHY?!

Upvotes: 0

Views: 302

Answers (2)

Andrew Li
Andrew Li

Reputation: 57964

Because the text (Python!) is of 7 length and lists are zero based (starting from 0) and the for loop is decreasing, you need to have -1.

The string "Python!" is 7 characters. Range is exclusive with the final number, thus the range is accounting for 6, 5, 4, 3, 2, 1, 0.

The length - 1 = 6, range of 6 to -1, where -1 is exclusive accounts for numbers 0 - 6. Because lists are 0 based, it accounts for all. With zero as the range's second argument, you only get the numbers 6, 5, 4, 3, 2, 1, which doesn't account for the whole word.

For example:

The word "Stack" has 5 letters. Once it is a list, it occupies the indices 0, 1, 2, 3, 4. You are looping through the whole word, thus you need to access the 0th element. To do that, the range must go to -1 exclusive.

For your loop:

>>> range(6, -1, -1)
[6, 5, 4, 3, 2, 1, 0]

Then, when you access it by doing:

text = "Python!"
for i in range(len(text)-1, -1, -1):
    print(text[i])

text[i] accesses all the individual characters and prints them, backwards.

Upvotes: 0

Karoly Horvath
Karoly Horvath

Reputation: 96266

The end point is omitted from the range.

>>> range(2,5)
[2, 3, 4]

To get the zeroth element, you need -1.

Upvotes: 2

Related Questions