Python program to sort strings by substring range
Last Updated :
22 Apr, 2023
Given a String List, sort by a range of substrings.
Input : test_list = ["geeksforgeeks", "best", "geeks", "preparation", "interview"], i, j = 1, 3
Output : ['geeksforgeeks', 'geeks', 'best', 'interview', 'preparation']
Explanation : "eek" < "eek" < "est" < "nte" < "rep".
Input : test_list = ["apple", "orange", "banana"], i, j = 2, 4
Output : ['orange', 'banana', 'apple']
Explanation : "ang" < "nan" < "ple".
Method #1 : Using sort() + slicing
In this, we perform the task of sorting using sort() and the task of extracting a range is done using slicing.
Python3
# Python3 code to demonstrate working of
# Sort Strings By Substring Range
# Using sort() + slicing
# helper function
def get_substr(test_str):
# getting range
return test_str[i : j]
# initializing list
test_list = ["geeksforgeeks", "best", "geeks", "preparation"]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
i, j = 1, 3
# calling func.
test_list.sort(key=get_substr)
# printing result
print("Strings after sorting : " + str(test_list))
OutputThe original list is : ['geeksforgeeks', 'best', 'geeks', 'preparation']
Strings after sorting : ['geeksforgeeks', 'geeks', 'best', 'preparation']
Time Complexity: O(nlogn)
Auxiliary Space: O(n)
Method #2 : Using lambda function + sort() + slicing
In this, we perform slicing using lambda function rather than calling external function.
Python3
# Python3 code to demonstrate working of
# Sort Strings By Substring Range
# Using lambda function + sort() + slicing
# initializing list
test_list = ["geeksforgeeks", "best", "geeks", "preparation"]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
i, j = 1, 3
# lambda function providing sort fnc.
test_list.sort(key=lambda test_str : test_str[i : j])
# printing result
print("Strings after sorting : " + str(test_list))
OutputThe original list is : ['geeksforgeeks', 'best', 'geeks', 'preparation']
Strings after sorting : ['geeksforgeeks', 'geeks', 'best', 'preparation']
Time Complexity: O(nlogn)
Auxiliary Space: O(n)
Method #3: Using the functools.cmp_to_key() function and sorted()
Step-by-step algorithm:
- Import the cmp_to_key function from the functools module.
- Create a list of strings test_list.
- Initialize i and j to 1 and 3 respectively.
- Define a comparison function cmp that takes two strings a and b as input and compares the substring of a and b from index i to index j. If the substring of a is less than the substring of b, return -1. If the substring of a is greater than the substring of b, return 1. Otherwise, return 0.
- Sort the list test_list using the sorted() function and the key argument set to cmp_to_key(cmp).
- Print the sorted list.
Python3
from functools import cmp_to_key
# initializing list
test_list = ["geeksforgeeks", "best", "geeks", "preparation"]
i, j = 1, 3
# printing original list
print("The original list is : " + str(test_list))
def cmp(a, b):
if a[i:j] < b[i:j]:
return -1
elif a[i:j] > b[i:j]:
return 1
else:
return 0
#initializing sorted
sorted_list = sorted(test_list, key=cmp_to_key(cmp))
# printing result
print(sorted_list)
OutputThe original list is : ['geeksforgeeks', 'best', 'geeks', 'preparation']
['geeksforgeeks', 'geeks', 'best', 'preparation']
Time complexity: O(n log n), where n is the length of the list test_list. This is because sorting using the sorted() function takes O(n log n) time.
Auxiliary Space: O(n), where n is the length of the list test_list. This is because we are creating a new list to store the sorted version of the input list.
Method #4:Using itemgetter() from operator module
- Importing the operator module to use itemgetter() function for sorting by substring range.
- Initializing a list test_list containing strings.
- Printing the original list.
- Initializing the range (start, end) for the substring.
- Sorting the list using the sorted() function and itemgetter() function from the operator module.
- The key argument takes operator.itemgetter(i, j) as a parameter. It sorts the list based on the substring from index i to index j.
- Printing the sorted list.
Python3
# importing operator module
import operator
# initializing list
test_list = ["geeksforgeeks", "best", "geeks", "preparation"]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
i, j = 1, 3
# sorting by substring range
test_list = sorted(test_list, key=operator.itemgetter(i, j))
# printing result
print("Strings after sorting : " + str(test_list))
OutputThe original list is : ['geeksforgeeks', 'best', 'geeks', 'preparation']
Strings after sorting : ['geeksforgeeks', 'geeks', 'best', 'preparation']
Time Complexity: O(n log n), where n is the length of the list test_list.
Auxiliary Space: O(n), where n is the length of the list test_list.
Method #6: Using list comprehension and sorted()
steps :
We initialize a list test_list with some strings.
We print the original list test_list.
We initialize two variables i and j to represent the start and end indices of the substring range we want to sort on.
We sort the list test_list using the sorted() function and a lambda function as the key. The lambda function extracts the substring range of each string in the list using the variables i and j. The sorted() function returns a new sorted list.
We update the original list test_list with the sorted list.
We print the updated list test_list.
Python3
# initializing list
test_list = ["geeksforgeeks", "best", "geeks", "preparation"]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
i, j = 1, 3
# sorting by substring range
test_list = sorted(test_list, key=lambda x: x[i:j+1])
# printing result
print("Strings after sorting : " + str(test_list))
OutputThe original list is : ['geeksforgeeks', 'best', 'geeks', 'preparation']
Strings after sorting : ['geeksforgeeks', 'geeks', 'best', 'preparation']
Time complexity: O(n log n), where n is the length of the list.
Auxiliary space: O(n), where n is the length of the list.
Similar Reads
Python Program to Sort a String
Sorting strings in Python is a common and important task, whether we need to organize letters alphabetically or systematically handle text data. In this article, we will explore different methods to sort a string starting from the most efficient to the least.Using sorted with join()sorted() function
2 min read
Python - Sort String by Custom Integer Substrings
Given a list of strings, sort strings by the occurrence of substring from list. Input : test_list = ["Good at 4", "Wake at 7", "Work till 6", "Sleep at 11"], subord_list = ["11", "7", "4", "6"] Output : ['Sleep at 11', 'Wake at 7', 'Good at 4', 'Work till 6'] Explanation : Strings sorted by substrin
5 min read
Python - Retain smallest subsets from strings
Given a set of strings, the task is to write a python program to retain strings from sets that are the smallest possible subset of strings found. Input : test_set = {'cbabca', 'cba', 'bdb', 'bdbab', 'abcx'} Output : {'bdb', 'abcx', 'cba'} Explanation : bdbab is removed as bdb ( smaller subset ) is r
2 min read
Python program to split a string by the given list of strings
Given a list of strings. The task is to split the string by the given list of strings. Input : test_str = 'geekforgeeksbestforgeeks', sub_list = ["best"] Output : ['geekforgeeks', 'best', 'forgeeks'] Explanation : "best" is extracted as different list element. Input : test_str = 'geekforgeeksbestfor
4 min read
Python | Remove the given substring from end of string
Sometimes we need to manipulate our string to remove extra information from the string for better understanding and faster processing. Given a task in which the substring needs to be removed from the end of the string using Python. Â Â Remove the substring from the end of the string using Slicing In
3 min read
Python program to Sort Strings by Punctuation count
Given the Strings list, sort by punctuations count. Input : test_list = ["gfg@%^", "is", "Best!"] Output : ['is', 'Best!', 'gfg@%^'] Explanation : 0 < 1 < 3, sorted by punctuation count. Input : test_list = ["gfg@%^", "Best!"] Output : [ 'Best!', 'gfg@%^'] Explanation : 1 < 3, sorted by pun
3 min read
Python - Remove after substring in String
Removing everything after a specific substring in a string involves locating the substring and then extracting only the part of the string that precedes it. For example we are given a string s="Hello, this is a sample string" we need to remove the part of string after a particular substring includin
3 min read
Python - String till Substring
When working with Python strings, we may encounter a situation where we need to extract a portion of a string that starts from the beginning and stops just before a specific substring. Let's discuss certain ways in which we can do this.Using split()The split() method is a simple and efficient way to
3 min read
Python Extract Substring Using Regex
Python provides a powerful and flexible module called re for working with regular expressions. Regular expressions (regex) are a sequence of characters that define a search pattern, and they can be incredibly useful for extracting substrings from strings. In this article, we'll explore four simple a
2 min read
Python program to list Sort by Number value in String
Given a List of strings, the task is to write a Python program to sort list by the number present in the Strings. If no number is present, they will be taken to the front of the list. Input : test_list = ["gfg is 4", "all no 1", "geeks over 7 seas", "and 100 planets"] Output : ['all no 1', 'gfg is 4
6 min read