-1

I have this Python code, is a recursive form of the Selection Sort Algorithm, but it doesn't work, can someone help me?

def selection(lista):
    return selection_aux(lista,0,len(lista))
def selection_aux(lista,i,n):
    if i == n or lista[0]==None:
        return lista
    else:
        num_menor = menor_f(lista,i,n,i)
        temporal = lista[i]
        lista[i] = num_menor
        print(num_menor)
        lista[num_menor] = temporal
        return selection_aux(lista,i+1,n)
def menor_f(lista,j,n,menor):
    if j == n:
        return menor
    if lista[j] < lista[menor]:
        menor = j
        return menor_f(lista,j+1,n,menor)

Test:

>>> selection([1,2,3])

Output

lista[num_menor] = temporal
TypeError: list indices must be integers, not NoneType
3
  • 3
    Can you please add more details as to how it is not working. Something like, what output you expected but what output you got, some logical error, or something like that. Commented May 30, 2015 at 21:42
  • Without reading your code carefully, isn't this a bit too long and complicated for something as simple as selection sort? Commented May 30, 2015 at 21:54
  • Yes, it is, but the idea is write that algorithm by using tail recursion !! Commented May 30, 2015 at 21:59

1 Answer 1

2

Your indentation was wrong, you did not return anything is if lista[j] < lista[menor] was False so you were setting num_menor to None as all python functions that don't return a value return None by default .

def menor_f(lista,j,n,menor):
    if j == n:
        return menor
    if lista[j] < lista[menor]:
        menor = j
    return menor_f(lista,j+1,n,menor) # dedent 

Cannot follow you variable names as I don't speak what seems to be french, but making the change works for selection([4,3,2])

print(selection([4,3,2]))
[2, 3, 4]

Fails for selection([ 8,3,4,2,5,6]) -> [3, 3, 4, 4, 5, 8] so you need to do some debugging.

Sign up to request clarification or add additional context in comments.

7 Comments

Actually is Spanish! I'm from Costa Rica!, Thank you for help me!!
Err.. What is dedent? A short for de-indent?
@BhargavRao, stick with me, I will lead you down the path of pyenlightenment ;)
Yep. You have been doing that since we first met :D
@BhargavRao,ah back when 12k+ imaginary rep points was only a dream!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.