Home > Software engineering >  List Problem in python to sort a list of string without using sort or sorted function
List Problem in python to sort a list of string without using sort or sorted function

Time:07-02

I am stuck in this list problem, I am unable to solve it.

list1= ["aaditya-2", "rahul-9", "shubhangi-4"]

I need to sort this list without using sort/sorted function.... and also it should sort on the basis of numbers at the last..

Output: ["aaditya-2", "shubhangi-4", "rahul-9"]

OR

["rahul-9", "shubhangi-4", "aaditya-2" ]

CodePudding user response:

You could try something like this:

def sort_arr(arr, function):
     arr2 = [function(i) for i in arr] # apply your function to all the elements in the array, in this case it is get the last digit
     for i in range(1, len(arr2)): # begin looping from the first index of the array to the last index
         k = arr2[i] # assign the value of the ith item to a variable
         j = i - 1 # keep track of the index begin considered
         while j >= 0 and k < arr2[j]: # while k is less than the item before it, do
                 arr2[j   1] = arr2[j] # shift the ith value one step to the front of the array
                 j -= 1
         arr2[j   1] = k # once the correct position has been found, position arr2[i] at its correct location
     return arr2 # return sorted array
print(sort_arr(list1, lambda x: int(x[-1]))) # the lambda gets the last digit and turns it into an integer

Learn more about lambda's here.

This is an implementation of insertion sort. Learn more about it here.

Hope this helps!

EDIT: Just realized this did not directly answer OP's question. Updated answer to match.

CodePudding user response:

As I understand it, it's a question of ordering. I don't think this is about implementing a sorting algorithm. Here I define a order function that works on two strings and orders them by last character. This is applied 3 times to sort 3-element list.

def order(a, b):
    return (b, a) if a[-1] > b[-1] else (a, b)
    
list1 = ["aaditya-2", "rahul-9", "shubhangi-4"]
a, b, c = list1

a, b = order(a, b)
a, c = order(a, c)
b, c = order(b, c)

list1 = [a, b, c] # ["aaditya-2", "shubhangi-4", "rahul-9"]

For reverse sort, just use < in the order function.

  • Related