![]() |
VOOZH | about |
Given a list of Strings, perform string split on the occurrence of prefix.
Input : test_list = ["geeksforgeeks", "best", "geeks", "and"], pref = "geek"
Output : [['geeksforgeeks', 'best'], ['geeks', 'and']]
Explanation : At occurrence of string "geeks" split is performed.Input : test_list = ["good", "fruits", "goodness", "spreading"], pref = "good"
Output : [['good', 'fruits'], ['goodness', 'spreading']]
Explanation : At occurrence of string "good" split is performed.
Method #1 : Using loop + startswith()
In this, we iterate each element of List, and check if new list has to be changed using startswith() by checking for prefix, and create new list if prefix is encountered.
The original list is : ['geeksforgeeks', 'best', 'geeks', 'and', 'geeks', 'love', 'CS'] Prefix Split List : [['geeksforgeeks', 'best'], ['geeks', 'and'], ['geeks', 'love', 'CS']]
Method #2 : Using loop + zip_longest() + startswith()
In this, we zip all the elements with their subsequent element sublist and check for prefix using startswith(), if found, result is appended.
The original list is : ['geeksforgeeks', 'best', 'geeks', 'and', 'geeks', 'love', 'CS'] Prefix Split List : [['geeksforgeeks', 'best'], ['geeks', 'and'], ['geeks', 'love', 'CS']]
Method #3 : Using list + recursion
Step-by-step approach:
[['geeksforgeeks', 'best'], ['geeks', 'and']]
Time complexity: O(n)
Auxiliary space: O(n)
Method #4 : Using loop + find() method
Step-by-step approach:
The original list is : ['geeksforgeeks', 'best', 'geeks', 'and', 'geeks', 'love', 'CS'] Prefix Split List : [['geeksforgeeks', 'best'], ['geeks', 'and'], ['geeks', 'love', 'CS']]
Time Complexity: O(N), where N length of list
Auxiliary Space: O(N)
Method #5: Using itertools.groupby() and zip():
Step-by-step approach:
The original list is : ['geeksforgeeks', 'best', 'geeks', 'and', 'geeks', 'love', 'CS'] Prefix Split List : [['geeksforgeeks', 'best'], ['geeks', 'and'], ['geeks', 'love', 'CS']]
Time complexity: O(n), where n is the length of the input list. This is because the algorithm iterates over each element in the input list once.
Auxiliary space: O(n), where n is the length of the input list. This is because the algorithm creates a list of sublists, where each sublist contains some or all of the elements from the input list. The size of this list of sublists is proportional to the length of the input list.
Method #6: Using the reduce() function from the functools module
Prefix Split List : [['geeksforgeeks', 'best'], ['geeks', 'and'], ['geeks', 'love', 'CS']]
Time complexity: O(n), where n is the length of the input list of strings, since it involves iterating through the list only once.
Auxiliary space: O(m), where m is the number of prefix occurrences in the input list, since it involves creating a new list for each prefix occurrence.