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 Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read