Try… except is wrong

Question:

I was working on a function that test functions and I found that y try except was wrong at all… In fact, when I am trying to test a sorting function (the one by selection) it returns me that the index was out of range and it’s not the case when I try the function independently with the same list…

Here is the code :

def verifyList(L: list) -> bool:
    for elm in range(len(L)):
        if L[elm] > L[elm + 1]:
            return False
        #
    return True

def tri_selection(L: list) -> list:
    """
    Recupere un element et l'échange avec le un plus grand
    """
    assert type(L) == list
    
    for i in range(len(L)):
        for j in range(len(L)):
            if L[i] <= L[j]:
                L[j], L[i] = L[i], L[j]
            #
        #
    #
    return L

Other functions that are not written because it’s unnecessary…

def __test__(L: list) -> str:
    assert type(L) == list

    functionsToTry = [tri_selection]

    for function in functionsToTry:
        try:
            if verifyList(function(L)) == True:
                print('[✓] ' + str(function.__name__) + ' : worked successfuly')
            else:
                print('[≃] ' + str(function.__name__) + ' : do not worked successfuly')
                continue
        except Exception as error:
            print('[✕] ' + str(function.__name__) + ' : ' + str(error))
        else:
            print(function(L))
__test__([3, 2, 1])

If you have an idea I’ll be glad to know it,

Thx

Asked By: Pax

||

Answers:

if L[elm] > L[elm + 1]: gives a list index out of range error when elm == len(L) - 1. The easiest fix is to change verifyList to:

def verifyList(L: list) -> bool:
    return L == sorted(L)

With this change your function passes the test.

Answered By: John Coleman
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.