Open In App

Python – Selective consecutive Suffix Join

Last Updated : 18 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 = [“Geeks-“, “for-“, “Geeks”, “is”, “best-“, “for”, “geeks”, suff = ‘-‘ 
Output : [‘Geeks-for-Geeks’, ‘is’, ‘best-for’, ‘geeks’] 
Explanation : Strings are joined to next which have “-” as suffix.

Input : test_list = [“Geeks*”, “for*”, “Geeks”, “is”, “best*”, “for”, “geeks”, suff = ‘*’ 
Output : [‘Geeks*for*Geeks’, ‘is’, ‘best*for’, ‘geeks’] 
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 = ["Geeks-", "for-", "Geeks", "is",
             "best-", "for", "geeks"]
 
# 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 : [‘Geeks-‘, ‘for-‘, ‘Geeks’, ‘is’, ‘best-‘, ‘for’, ‘geeks’] The joined result : [‘Geeks-for-Geeks’, ‘is’, ‘best-for’, ‘geeks’]

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 = ["Geeks-", "for-", "Geeks", "is", "best-", "for", "geeks"]
suff = '-'
result = selective_consecutive_suffix_join(test_list, suff)
print(result)


Output

['Geeks-for-Geeks', 'is', 'best-for', 'geeks']

Time Complexity: O(n)

Auxiliary Space: O(n)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads