Python Based Quickselect Implementation Resulting In Error
I have small python code that implements the quickselect discussed here. import random def Quickselect(A, k): if not A: return pivot = random.choice(A) i = 0
Solution 1:
Your error occurs because randrange
breaks when the range is empty (i.e. randrange(1, 1)
).
Use random.choice
instead and change k <= len(A1)
to k < len(A1)
:
def quick_select(A, k):
pivot = random.choice(A)
A1 = []
A2 = []
for i in A:
if i < pivot:
A1.append(i)
elif i > pivot:
A2.append(i)
else:
pass # Do nothing
if k <= len(A1):
return Quickselect(A1, k)
elif k > len(A) - len(A2):
return Quickselect(A2, k - (len(A) - len(A2)))
else:
return pivot
Post a Comment for "Python Based Quickselect Implementation Resulting In Error"