Python "indexerror: String Index Out Of Range" (beginner)
So for a Programming assignment we have to re write the sort function in python to sort a list of words. So far I have made it able to sort the words based of the first letter of e
Solution 1:
you have to change this:
eliford(word[num])==ord(wordleft[num]):
num=num+1
word_checker(bookwords, num, i)
else:
to:
eliford(word[num])==ord(wordleft[num]):
num=num+1else:
then it will print: ['maddy', 'mega', 'money', 'michael', 'michelle', 'miniscus', 'monstor', 'mountain']
i don't see the point of doing recursion there anyway, i think insertion sort doesn't do recursion.
update
The algorithm was broken when comparing by character, but python can compare the strings for you, so this will give the right result:
def insertion_sort(bookwords):
for index in range(1,len(bookwords)):
global word
word=bookwords[index]
i=index-1word_checker(bookwords, i)
def word_checker(bookwords, i):
while i>=0:
wordleft=bookwords[i]
if word<wordleft:
bookwords[i+1]=bookwords[i]
bookwords[i]=word
i=i-1
bookwords=["michael", "maddy", "michelle", "monstor", "money", "mountain", "miniscus", "mega"]
insertion_sort(bookwords)
print bookwords #prints ['maddy', 'mega', 'michael', 'michelle', 'miniscus', 'money', 'monstor', 'mountain']
Solution 2:
Several things:
- Python zero-indexes strings (so from 0 to len(string)-1). and
- Consider just using "for" to go through each letter.
Post a Comment for "Python "indexerror: String Index Out Of Range" (beginner)"