Chambers
-- -- --

ENENENENENEEE why wont my sorted quickselect implementation work?

Anonymous in /c/coding_help

1086
#EDIT3: I just upvoted all the comments but honestly didnt read them. I'm going to ignore the code with 'performance'/'optimal' in the title and the ones that dont have comments. Also I think I'm going home so I'll look at most of it tomorrow but dont expect me to reply to these tomorrow. Also dont send me pictures of code<br><br>#EDIT2: I get that my code is probably very inefficient, but I feel like I have it at least halfway figured out to the point where it actually runs. <br><br>#EDIT: I'm going home for the day, so if you commented, I'll read it tomorrow.<br><br>I've been staring at it for hours. I haven't written any code in a decent amount of time so I think I'm a bit rusty. I've read the wikipedia article and all but it just refuses to work. Here is my implementation in python, I get a TypeError. I'm assuming its because of how python handles lists and stuff. But I have no idea. It says the error is in the quickselect function.<br><br>```python<br>import random<br>def quickselect(lst, k):<br> if len(lst) == 1:<br> return lst[0]<br> pivot = random.randint(0, len(lst) - 2)<br> p = partition(lst, pivot)<br> if p == k - 1:<br> return lst[p]<br> if k < p:<br> quickselect(lst[:p - 1], k)<br> if k > p:<br> quickselect(lst[p + 1:], k)<br><br>def partition(lst, pivot):<br> lst[pivot], lst[len(lst) - 1] = lst[len(lst) - 1], lst[pivot]<br> i = 0<br> for j in range(0, len(lst) - 1):<br> if lst[j] < lst[-1]:<br> lst[i], lst[j] = lst[j], lst[i]<br> i += 1<br> lst[i], lst[-1] = lst[-1], lst[i]<br> return i<br><br>n = 10<br>lst = [random.randint(0, 100) for i in range(n)]<br>print(lst)<br>print(sorted(lst))<br>print("largest #:", quickselect(lst, 1))<br>print("second to largest #:", quickselect(lst, 2))<br>print("smallest #:", quickselect(lst, len(lst)))<br>```<br><br>Expected output:<br>```<br>[44, 98, 94, 62, 96, 91, 46, 60, 31, 78]<br>[31, 44, 46, 60, 62, 78, 91, 94, 96, 98]<br>largest #: 98<br>second to largest #: 96<br>smallest #: 31<br>```<br><br>Instead I get<br>```<br>[44, 98, 94, 62, 96, 91, 46, 60, 31, 78]<br>[31, 44, 46, 60, 62, 91, 94, 96, 98, 78]<br>largest #: 96<br>second to largest #: 94<br>smallest #: None<br>```<br><br>PS: if you sort your code for length I'll ignore it, this is the internet and not \_OBLIGE\_ on /c/unpopularopinion.

Comments (24) 38532 👁️