Python | Prefix extraction depending on size
Last Updated :
17 Apr, 2023
Sometimes, while working with Python, we can have a problem in which we need to extract prefix from a string. This can be conditional sometimes, and we just need to extract specific length substring if size of string is larger than some N. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop This is brute force way to perform this task, in which we extract the string according to size using a loop.
Python3
test_list = [ 'geeksforgeeks' , 'is' , 'best' , 'for' , 'geeks' ]
K = 2
N = 4
print ("The original list is : " + str (test_list))
res = []
for idx in test_list:
if len (idx) > = N:
res.append(idx[:K])
print (" List after prefix extraction : " + str (res))
|
Output :
The original list is : ['geeksforgeeks', 'is', 'best', 'for', 'geeks']
List after prefix extraction : ['ge', 'be', 'ge']
Time Complexity: O(n), where n is the length of the input list. This is because we’re using the loop which has a time complexity of O(n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.
Method #2 : Using filter() + lambda This task can also be performed using combination of above functions. In this, we perform the task of checking using filter(), and extraction is done in shorter way using list comprehension.
Python3
test_list = [ 'geeksforgeeks' , 'is' , 'best' , 'for' , 'geeks' ]
K = 2
N = 4
print ("The original list is : " + str (test_list))
res = [sub[:K] for sub in filter ( lambda ele : len (ele) > = N, test_list)]
print (" List after prefix extraction : " + str (res))
|
Output :
The original list is : ['geeksforgeeks', 'is', 'best', 'for', 'geeks']
List after prefix extraction : ['ge', 'be', 'ge']
Method #3: Using list comprehension with conditional statement
Step-by-step approach:
- Initialize the list test_list with some string elements.
- Initialize the values of K and N.
- Print the original list.
- Use a list comprehension to extract the prefixes of length K from the words in test_list if the length of the word is greater than or equal to N.
- Print the result.
Below is the implementation of the above approach:
Python3
test_list = [ 'geeksforgeeks' , 'is' , 'best' , 'for' , 'geeks' ]
K = 2
N = 4
print ( "The original list is : " + str (test_list))
res = [sub[:K] for sub in test_list if len (sub) > = N]
print ( "List after prefix extraction : " + str (res))
|
Output
The original list is : ['geeksforgeeks', 'is', 'best', 'for', 'geeks']
List after prefix extraction : ['ge', 'be', 'ge']
Time complexity: O(n), where n is the number of elements in the list test_list.
Auxiliary space: O(m), where m is the number of elements in the new list res.
Share your thoughts in the comments
Please Login to comment...