-3

My code is giving me an error saying the index is out of range on line 9. Here is my code:

s = 'aba'
letter = ''
substring = ''

i = 0

while(i <= len(s)):
    prev_letter = s[0]
    letter = s[i]

    if letter <= prev_letter:
        substring += letter
        prev_letter = letter

    i += 1
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
Jordan Baron
  • 25
  • 1
  • 1
  • 9

2 Answers2

5

Change while(i <= len(s): to while(i < len(s)):, or to while(i <= len(s)-1):

In Python, a string is a single-dimensional array of characters. Indexes in Python programming start at 0. This means that the maximum index for any string will always be len(s)-1. In your code, i will eventually be equal to len(s), which is one element higher than the maximum.

As a side note, it would probably be beneficial to use a for loop rather than a while loop in your code. Your code can be replaced with this:

s = 'aba'
letter = ''
substring = ''

i = 0

for i in range(len(s)):
    prev_letter = s[0]
    letter = s[i]

    if letter <= prev_letter:
        substring += letter
        prev_letter = letter
Douglas
  • 1,304
  • 10
  • 26
  • 1
    Not every programming languages are `zero-based`! in [this](http://stackoverflow.com/a/1499795/4834682) you can find a list of `one-based` indexing languages. – Null Jan 11 '17 at 18:32
  • 1
    Oh yeah, I meant to specify Python. There are some that start at 1, like TI-BASIC. I'll edit that now. – Douglas Jan 12 '17 at 14:15
1

As other people have indicated, s[s.Length] isn't actually a valid index; indices are in the closed interval [0, length - 1] (i.e. the last valid index is length - 1 and the first index is 0). Note that this isn't true for every language (there are languages where the first index is 1), but it's certainly true for Python.

Think about what an array is and how it's implemented: it's just a series of consecutive memory locations. The index is an offset from the initial memory address, not the item number. That's why the first item has an index of 0 - there's no offset from the address of the first item (by definition). However, the 5th item's address, for example, is (address of the first item) + (4 * offset size). That's why you can access an arbitrary item in an array in constant time. (This is a "holdover" from C/C++ of sorts).