Python – Selective consecutive Suffix Join
Given a list of elements, the task is to write a Python program to perform a join of consecutive strings according to the suffix of each string.
Input : test_list = [“Beginner-“, “for-“, “Beginner”, “is”, “best-“, “for”, “Beginner”, suff = ‘-‘
Output : [‘Beginner-for-Beginner’, ‘is’, ‘best-for’, ‘Beginner’]
Explanation : Strings are joined to next which have “-” as suffix.Input : test_list = [“Beginner*”, “for*”, “Beginner”, “is”, “best*”, “for”, “Beginner”, suff = ‘*’
Output : [‘Beginner*for*Beginner’, ‘is’, ‘best*for’, ‘Beginner’]
Explanation : Strings are joined to next which have “*” as suffix.
Approach : Using loop + endswith() + join()
In this we perform the task of joining using join() and endswith() performs the task of conditional checks for suffix as defined.
Python3
# Python3 code to demonstrate working of # Selective consecutive Suffix Join # Using loop + endswith() + join() # initializing list test_list = [ "Beginner-" , "for-" , "Beginner" , "is" , "best-" , "for" , "Beginner" ] # printing original list print ( "The original list is : " + str (test_list)) # initializing suffix suff = '-' res = [] temp = [] for ele in test_list: temp.append(ele) # conditionally test values if not ele.endswith(suff): res.append(''.join(temp)) temp = [] if temp: res.append(''.join(temp)) # printing result print ( "The joined result : " + str (res)) |
Output:
The original list is : [‘Beginner-‘, ‘for-‘, ‘Beginner’, ‘is’, ‘best-‘, ‘for’, ‘Beginner’] The joined result : [‘Beginner-for-Beginner’, ‘is’, ‘best-for’, ‘Beginner’]
The time and space complexity for all the methods are the same:
Time Complexity: O(n)
Space Complexity: O(n)
Approach : Using re
In this approach, we use the re library to compile a regular expression pattern to match the suffix. The re.search function is used to check if a string ends with the given suffix. If the string doesn’t end with the suffix, we append the joined string to the result and reset the temporary list.
Python3
import re def selective_consecutive_suffix_join(test_list, suff): pattern = re. compile (f "{suff}$" ) res = [] temp = [] for ele in test_list: temp.append(ele) if not pattern.search(ele): res.append(''.join(temp)) temp = [] if temp: res.append(''.join(temp)) return res test_list = [ "Beginner-" , "for-" , "Beginner" , "is" , "best-" , "for" , "Beginner" ] suff = '-' result = selective_consecutive_suffix_join(test_list, suff) print (result) |
['Beginner-for-Beginner', 'is', 'best-for', 'Beginner']
Time Complexity: O(n)
Auxiliary Space: O(n)