Why I can't return function value? Return gives "none"?
Question:
def sel(unsort,current):
if len(unsort) == 0:
return current
temp = unsort[0]
for i in range(len(unsort)):
if unsort[i]<temp:
temp = unsort[i];
unsort.remove(temp)
current = current + [temp];
sel(unsort,current)
Above will define a function selection sort.
a = [4,3,2,1];
print(sel(a, []))
When I run the program on python, it print “None”. The function should return current
as a list. What have I done wrong here?
Answers:
When you recursively call sel
, you ignore the return value.
Change it to return
:
return sel(unsort, current)
def sel(unsort,current):
if len(unsort) == 0:
return current
temp = unsort[0]
for i in range(len(unsort)):
if unsort[i]<temp:
temp = unsort[i];
unsort.remove(temp)
current = current + [temp];
sel(unsort,current)
Above will define a function selection sort.
a = [4,3,2,1];
print(sel(a, []))
When I run the program on python, it print “None”. The function should return current
as a list. What have I done wrong here?
When you recursively call sel
, you ignore the return value.
Change it to return
:
return sel(unsort, current)