DMaxter
DMaxter

Reputation: 178

Index out of range - Python

I was programming at CodeWars using Kata, when i got this error:

Traceback:
   in 
   in title_case
IndexError: list index out of range

Here is my code:

def title_case(title, minor_words=1):
    string = title.split()
    outList = []
    if minor_words != 1:
        split = minor_words.split()
        minor = [x.lower() for x in split]
    out = ""
    for i in range(0, len(string)):
        word = ""
        for j in range(0,len(string[i])):
            elem = ""
            elem += string[i][j]
            if j == 0:
                word += elem.upper()
            else:
                word += elem.lower()
        if i != len(string)-1:
            outList.append(word+" ")
        else:
            outList.append(word)
    list = [x.lower() for x in outList]
    print ((list[0]))#Just for debug
    if minor_words != 1:
        for i in range(0, len(outList)):
            if (list[i] in minor):
                print("OI")#Just for debug
                out += list[i]
            else:
                out += outList[i]
    return out

Well, this happened when trying to execute the code, of course! One way to initialize this function would be:

title_case('a clash of KINGS', 'a an the of')

Well the 0 elemeny exists, but it says it doesn't, I don't know why, because when I write "print(list)" it shows me the elements of list, in this case, "['a', 'clash', 'of', 'kings']".

What can I do?

Upvotes: 0

Views: 53

Answers (1)

Carl
Carl

Reputation: 2067

Okay, so based on reading this code I think the result you desire from: title_case('a clash of KINGS', 'a an the of') is: A Clash of Kings

So it looks like you are stepping through a lot of hoops trying to get there. While I was going through the code it took me a while to see what was actually happening. I also took the liberty to make your variables more consistently named. Rather than mixing caseLetter and case_letter randomly I made it consistent. I also made your loops easier to read. Also for the minorWords argument. Might as well have it passed as a list rather than converting it to a list inside the function. Anyway, I hope this is of help.

def titleCase(title, minorWords=[]):
    titleList = [x.lower() for x in title.split()]
    outList = []

    for Word in titleList:
        if Word not in minorWords:
            Word = Word.capitalize()
        outList.append(Word)

    return " ".join(outList)

TitleCased = titleCase("a clash of KINGS", ["an", "the", "of"])
print (TitleCased)

Which outputs A Clash of Kings, which I believe, based on your question and how I understood your code is what you wanted to achieve? Or if you include a in your minorWords, it would be:

a Clash of Kings

Regardless, hope this answers your question!

Upvotes: 1

Related Questions