Python – Kth Valid String
Last Updated :
09 Apr, 2023
Sometimes while dealing with data science, we need to handle a large amount of data and hence we may require shorthands to perform certain tasks. We handle the Null values at preprocessing stage and hence sometimes require to check for the Kth valid element. Let’s discuss certain ways in which we can find the Kth Non-Empty String.
Method #1 : Using next() + list comprehension The next function returns the iterator and hence its more efficient that conventional list comprehension and the logic part is handled using list comprehension which checks for the last None value.
Python3
test_list = [" ", " ", " Akshat ", " Nikhil"]
print ( "The original list : " + str (test_list))
K = 2
test_list = iter (test_list)
for idx in range ( 0 , K):
res = next (sub for sub in test_list if sub)
print ( "The Kth non empty string is : " + str (res))
|
Output
The original list : ['', '', 'Akshat', 'Nikhil']
The Kth non empty string is : Nikhil
Time Complexity: O(n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”.
Method #2 : Using filter() The filter function can be used to find the Non empty strings and the Kth index is returned to get the first string among those. Works only with Python 2.
Python
test_list = [" ", " ", " Akshat ", " Nikhil"]
print ( "The original list : " + str (test_list))
K = 2
res = filter ( None , test_list)[K - 1 ]
print ( "The Kth non empty string is : " + str (res))
|
Output :
The original list : ['', '', 'Akshat', 'Nikhil']
The Kth non empty string is : Nikhil
Time Complexity: O(n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_list”.
Method #3: Using list comprehension with enumerate
This method uses list comprehension along with the enumerate function to find the Kth non-empty string. The enumerate function is used to keep track of the index of the non-empty strings in the original list.
Python3
test_list = [" ", " ", " Akshat ", " Nikhil"]
print ( "The original list : " + str (test_list))
K = 2
res = [sub for i, sub in enumerate (test_list) if sub][K - 1 ]
print ( "The Kth non empty string is : " + str (res))
|
Output
The original list : ['', '', 'Akshat', 'Nikhil']
The Kth non empty string is : Nikhil
Time Complexity and Auxiliary space are O(n) and O(n) respectively.
Share your thoughts in the comments
Please Login to comment...