The program is supposed to use quick select and return the median of a set of integer values.
Question: When I run the program, it tells me that k is not defined. How should I define k to get the median?
def quickSelect(lines,k):
if len(lines)!=0:
pivot=lines[(len(lines)//2)]
smallerlist=[]
for i in lines:
if i<pivot:
smallerlist.append(i)
largerlist=[]
for i in lines:
if i>pivot:
largerlist.append(i)
m=len(smallerlist)
count=len(lines)-len(smallerlist)-len(largerlist)
if k >= m and k<m + count:
return pivot
elif m > k:
return quickSelect(smallerList,k)
else:
return quickSelect(largerList, k - m - count)
The code seems to be working fine, after a minor correction. smallerlist and largerlist had a typo.
elif m > k:
return quickSelect(smallerList,k)
else:
return quickSelect(largerList, k - m - count)
should be changed by
elif m > k:
return quickSelect(smallerlist,k)
else:
return quickSelect(largerlist, k - m - count)
This is the final corrected code, which runs just fine.
def quickSelect(lines,k):
if len(lines)!=0:
pivot=lines[(len(lines)//2)]
smallerlist=[]
for i in lines:
if i<pivot:
smallerlist.append(i)
largerlist=[]
for i in lines:
if i>pivot:
largerlist.append(i)
m=len(smallerlist)
count=len(lines)-len(smallerlist)-len(largerlist)
if k >= m and k<m + count:
return pivot
elif m > k:
return quickSelect(smallerlist,k)
else:
return quickSelect(largerlist, k - m - count)
Hope it helps