0
Can anyone provide me the python code for finding the kth smallest element from a list using partition method?
Code for the partition https://code.sololearn.com/cVLrSIJMfp8S/?ref=app
8 Answers
0
def partition(l,k):
return sorted(set(l))[k-1]
a=[12,45,34,22,11,65,23,12,10]
k=4 #kth smallest item
print(sorted(a))
print(partition(a,k))
0
Akbar Ali Quazi can you please elaborate...as I am beginner....also please insert the code.
0
First of all, Python is not like c/cpp or java. So don't apply any of those logic which u implement on those programming languages.
Now let's understand the code.
We have a list of numbers name 'a' . To get kth smallest item from given list, first u need to get smallest item from the list.
So if we sort the list then we can have smallest and largest number. In Python we can sort any collection using sorted() function it returns a list.
Now, there is possible case if list contains duplicate items, so we need to remove those item.
Set() function removes all the duplicate item from a collection.
Now we have sorted and distinct list.
It's tym to get kth item from list. It means Kth number item will be kth smallest item from the beginning of the list.
To get item from list we use list [index]. Bcz index start from zero so we have to one minus for kth item.
0
I had mentioned in the question that I need to find the kth smallest element using the partition method not by just sorting it.
The partition method is the one that we use in quick sort.
I need to know the full code and for the reference I had provided the python partition code.
0
Thn you should try it on C/Cpp java. Python is not for implementing those logics. Python offer u modern solutions not traditional.
0
Yeah!..but traditional methods can be used even in python though it is useless
0
For better understanding, you should go with C. No doubt u can code in python as well.
0
I haven't studied C
That's why I want the python code.
Can you please provide it?