Krowzer
Krowzer

Reputation: 3

Python 2.7 "list index out of range"

I keep getting "IndexError: list index out of range", the code does fine with things like "s = 'miruxsexxzlbveznyaidekl'" but this particular length makes it throw an error. Can anyone help me understand what I did wrong here, not just give me the answer? (I'd like to not have to come back and ask more question haha)

__author__ = 'Krowzer'

s = 'abcdefghijklmnopqrstuvwxyz'

def alpha(x):
    current_substring = []
    all_substring = []

    for l in range(len(x) - 1):
        current_substring.append(x[l])
        if x[l + 1] < x[l]:
            all_substring.append(current_substring)
            #print("current: ", current_substring)
            current_substring = []

    #print(all_substring)

    largest = all_substring[0]
    for i in range(len(all_substring)):
        if len(all_substring[i]) > len(largest):
            largest = all_substring[i]
    answer = ''.join(largest)
    print('Longest substring in alphabetical order is: ' + answer )

alpha(s)

Upvotes: 0

Views: 341

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1271191

I can try to explain what is going on.

You are trying to find the longest substring in alphabetical order by looking for the end of the substring. Your definition of end is that there is a character less than the last character in the string -- something in descending alphabetical order.

Your example substring has no such string. So, the initial loop never finds an end to it. As a result, all_substring[] is empty and trying to get any element out of it (such as all_substring[0]) generates an error.

You can fix the code yourself. The easiest is probably just to check if it is empty. If so, then the entire original string is the match.

EDIT:

On second thought, there are two errors in the code. One is that the last character is not being considered. The second is that the final substring is not being considered.

def alpha(x):
    current_substring = []
    all_substring = []

    for l in range(len(x)):
        current_substring.append(x[l])
        if l < len(x) - 1 and x[l + 1] < x[l]:
            all_substring.append(current_substring)
            #print("current: ", current_substring)
            current_substring = []

    print(all_substring)
    all_substring.append(current_substring)
    largest = all_substring[0]
    for i in range(len(all_substring)):
        if len(all_substring[i]) > len(largest):
            largest = all_substring[i]
    answer = ''.join(largest)
    print('Longest substring in alphabetical order is: ' + answer )

Upvotes: 1

Related Questions