Python | Remove Redundant Substrings from Strings List
Given list of Strings, task is to remove all the strings, which are substrings of other Strings.
Input : test_list = [“Gfg”, “Gfg is best”, “Geeks”, “for”, “Gfg is for Geeks”]
Output : [‘Gfg is best’, ‘Gfg is for Geeks’]
Explanation : “Gfg”, “for” and “Geeks” are present as substrings in other strings.
Input : test_list = [“Gfg”, “Geeks”, “for”, “Gfg is for Geeks”]
Output : [‘Gfg is for Geeks’]
Explanation : “Gfg”, “for” and “Geeks” are present as substrings in other strings.
Method #1 : Using enumerate() + join() + sort()
The combination of above functions can be used to solve this problem. In this, first the sorting is performed on length parameter, and current word is checked with other words, if it occurs as substring, if yes, its excluded from filtered result.
Python3
# Python3 code to demonstrate working of # Remove Redundant Substrings from Strings List # Using enumerate() + join() + sort() # initializing list test_list = [ "Gfg" , "Gfg is best" , "Geeks" , "Gfg is for Geeks" ] # printing original list print ( "The original list : " + str (test_list)) # using loop to iterate for each string test_list.sort(key = len ) res = [] for idx, val in enumerate (test_list): # concatenating all next values and checking for existence if val not in ', ' .join(test_list[idx + 1 :]): res.append(val) # printing result print ( "The filtered list : " + str (res)) |
The original list : ['Gfg', 'Gfg is best', 'Geeks', 'Gfg is for Geeks'] The filtered list : ['Gfg is best', 'Gfg is for Geeks']
Method #2 : Using list comprehension + join() + enumerate()
The combination of above functions can be used to solve this problem. In this, we perform task in similar way as above just the difference being in more compact way in list comprehension.
Python3
# Python3 code to demonstrate working of # Remove Redundant Substrings from Strings List # Using list comprehension + join() + enumerate() # initializing list test_list = [ "Gfg" , "Gfg is best" , "Geeks" , "Gfg is for Geeks" ] # printing original list print ( "The original list : " + str (test_list)) # using list comprehension to iterate for each string # and perform join in one liner test_list.sort(key = len ) res = [val for idx, val in enumerate (test_list) if val not in ', ' .join(test_list[idx + 1 :])] # printing result print ( "The filtered list : " + str (res)) |
The original list : ['Gfg', 'Gfg is best', 'Geeks', 'Gfg is for Geeks'] The filtered list : ['Gfg is best', 'Gfg is for Geeks']
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Space Complexity: O(n)
Please Login to comment...