问题
Code:
import math
import time
import random
class SortClass(object):
def sort1(self, l):
if len(l)==1:
return l
elif len(l)==2:
if l[0]<l[1]:
return l
else:
return l[::-1]
else:
pivot=math.floor(len(l)/2)
a=l[pivot:]
b=l[:pivot]
a2=self.sort1(a)
b2=self.sort1(b)
if a2==None or b2==None:
a2=[]
b2=[]
return (a2+b2).sort()
return []
Sort=SortClass()
x=[20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1]
print(Sort.sort1(x))
The code outputs None even though it should return an empty list in two cases:
return []
and
a2=self.mergeSort(a)
b2=self.mergeSort(b)
if a2==None or b2==None:
a2=[]
b2=[]
return (a2+b2).sort()
Details:
The code is for a list sorting module I am making for python practice (I am relatively new at python). sort1
is a modified mergesort.
回答1:
@reut got to it first but
return sorted(a2+b2)
not
return (a2+b2).sort()
Additionally
if a2 == None or b2 == None:
a2 = []
b2 = []
Should be
if a2 == None:
a2 = []
if b2 == None:
b2 = []
Your setting both to [] if either is none meaning if a2 is [1] and b2 is none your throwing away a2. I'm guessing this is unintended.
Also in your code you have an uppercase S in the lower sortClass
in addition return[] will never return, the above else does not allow it to.
回答2:
list.sort returns None
(sorts in-place):
>>> [].sort() is None
True
You're using it here:
return (a2+b2).sort()
Use sorted to sort to a new list and not in-place:
return sorted(a2+b2)
来源:https://stackoverflow.com/questions/34710129/sort-returns-none