当前位置: 动力学知识库 > 问答 > 编程问答 >

Python IndexError handling

问题描述:

def kindDetector(list):

for i in range(0,len(list)):

if type(list[i]) != type('a'):

return 0

return 1

def findWords(list,i):

if i == 0:

return list[0]

if list[i] < findWords(list,i-1):

return list.pop(i)

else:

return list.pop(i-1)

def sortWords(list,i):

result=[]

while i >= 0:

result.append(findWords(list,i))

i -=1

print(result)

list = input('Enter your words, with a space between.\t').split()

i = len(list)-1

if kindDetector(list):

sortWords(list,i)

But here i only can enter 2 words when i try it with 3 this happens:

Traceback (most recent call last):

File "C:/Users/honey/Desktop/python/selfMade/sortWords.py", line 26, in <module>

sortWords(list,i)

File "C:/Users/honey/Desktop/python/selfMade/sortWords.py", line 18, in sortWords

result.append(findWords(list,i))

File "C:/Users/honey/Desktop/python/selfMade/sortWords.py", line 10, in findWords

if list[i] < findWords(list,i-1):

IndexError: list index out of range

网友答案:

You have mixed BubbleSort (i.e. comparing neighbors and trying to shift them one at a time until the list is sorted) with SelectionSort (i.e. find the smallest item from an unsorted list and append it to the front of a resulting list).

And, there are a few more problems here:

  • Python passes variables by reference, which means that your functions receive a handle for the original list instead of a copy. If you change the list (what your pop() calls do) while iterating, you will run into index errors.

  • Your findWords function is flawed. You iterate from back to front and check whether the current element is lexicographically smaller than its predecessor (i.e. left neighbor). You probably want to change the pop-calls to return statements, don't you?

I have quickly implemented a few basic sorting algorithms (no error handling, type comparator usage etc whatsoever):

def is_list_of_strings(lst):
    for i in range(0,len(lst)):
        if type(lst[i]) not in (str, unicode):
            return False
    return True

def is_sorted(lst):
    if len(lst) < 2:
        return True
    for i in range(len(lst) - 1):
        if not lst[i] < lst[i + 1]:
            return False
    return True

def selection_sort(lst):
    l = lst[:] # Copy!
    r = []
    while len(l):
        r.append(l.pop(l.index(min(l))))
    return r

def insertion_sort(lst):
    l = lst[1:] # Copy!
    r = [lst[0]]
    for e in l:
        inserted = False
        for w in r:
            if e < w:
                r.insert(r.index(w), e)
                inserted = True
                break
        if not inserted:
            r.append(e)
    return r

def bubble_sort(lst):
    l = lst[:] # Copy!
    while not is_sorted(l):
        for i in range(len(l) - 1):
            if l[i] > l[i + 1]:
                tmp = l[i]
                l[i] = l[i + 1]
                l[i + 1] = tmp
    return l

if __name__ == '__main__':
    lst = ['aaa', 'aba', 'aab', 'baz', 'bar']

    print('Valid list of strings?', is_list_of_strings(lst))
    print(lst, is_sorted(lst))

    bbl = bubble_sort(lst)
    ins = insertion_sort(lst)
    sel = selection_sort(lst)

    print(bbl, is_sorted(bbl))
    print(ins, is_sorted(ins))
    print(sel, is_sorted(sel))

Have a look at them, try to understand them and have a read about these three techniques online. And then try to re-implement them using your own functions. Have fun coding :)

分享给朋友:
您可能感兴趣的文章:
随机阅读: