Given a list of percentage, write a Python program to sort the given list in ascending order. Let’s see different ways to do the task. Code #1: Chops ‘%’ in string and convert it into float.
Python3
# Python code to sort list of percentage # List initializationInput =['2.5 %', '6.4 %', '91.6 %', '11.5 %']# removing % and converting to float# then apply sort functionInput.sort(key = lambda x: float(x[:-1]))# printing outputprint(Input) |
['2.5 %', '6.4 %', '11.5 %', '91.6 %']
Time Complexity: O(nlogn), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Code #2:
Python3
# Python code to sort list of percentage # List initializationInput =['2.5 %', '6.4 %', '91.6 %', '11.5 %']# Temporary list initializationtemp = []# removing % signfor key in Input: temp.append((key[:-1]))# sorting list of floattemp = sorted(temp, key = float)# Output list initializationoutput = []# Adding percentage signfor key in temp: output.append(key + '%')# printing outputprint(output) |
['2.5 %', '6.4 %', '11.5 %', '91.6 %']
Time Complexity: O(nlogn), where n is the length of Input list.
Auxiliary Space: O(n), where n is the number of elements in output list
Using re:
Here is another approach using the re module and a lambda function:
- Import the re module
- Define a lambda function that takes a string as input and uses a regular expression to extract the float value of the string
- Use the sorted() function to sort the input list using the lambda function as the key
Here is the implementation of this approach:
Python3
import redef sort_percentage_list(lst): # Define a lambda function that takes a string as input and uses a regular expression to extract the float value of the string key = lambda x: float(re.search(r"(\d+\.\d+)", x).group()) # Use the sorted function to sort the input list using the lambda function as the key return sorted(lst, key=key)# Test the functionlst = ['2.5 %', '6.4 %', '91.6 %', '11.5 %']print(sort_percentage_list(lst))#This code is contributed by Edula Vinay Kumar Reddy |
['2.5 %', '6.4 %', '11.5 %', '91.6 %']
The regular expression r”(\d+\.\d+)” will match and extract any float value in the string. For example, it will match ‘2.5’ in the string ‘2.5 %’. The group() method of the Match object returned by re.search() will then return the matched
Time complexity: O(nlogn)
Auxiliary Space: O(1)
