Home > OS >  Try... except is wrong
Try... except is wrong

Time:11-26

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

CodePudding user response:

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.

  • Related