user 3 50
user 3 50

Reputation: 13

Number sorting by a recursive function

Could anyone help me figure out why my recursive function isn't working? I am trying to sort a list of numbers so that it would start with the biggest one, and continue in an descending order.

def sort(L):
  newlist=[]
  if len(L) == 0:
    return []
  else:
    z = max(L)
    a=newlist.append(z)
    g=L.remove(z)
    return a, sort(g)


print sort([1,5,8,49,29,2])

Upvotes: 0

Views: 54

Answers (1)

Adi Levin
Adi Levin

Reputation: 5243

L.remove(z) and newlist.append(z) both return None. If you want g to be the same as L but without the z element, you could write:

g=list(l)
g.remove(z)

Also, you are returning multiple return values, when I think you want to return a list. The following seems to work:

def sort(L):
  if len(L) == 0:
    return []
  else:
    z = max(L)
    g = list(L)
    g.remove(z)
    return [z] + sort(g)

if __name__ == '__main__':
    s = sort([1,5,8,49,29,2])
    print s

Upvotes: 2

Related Questions