Athlete Sort - HackerRank Solution in Python

Featured image

Athlete sort - HackerRank is a medium-difficulty problem of Python based on sorting and nested lists. It is part of the Python practice problems of HackerRank. In this post, we will see how we can solve this challenge in Python

Problem Statement

In this problem statement, we have to sort the given spreadsheet with respect to the Kth column. The spreadsheet consists of N rows and M columns. We have to print the sorted table.

Suppose the given spreadsheet is

Sr. No. Age Marks Height Weight Roll No. class
1 10 12 170 40 3 8
2 12 12 180 50 1 9
3 8 10 160 45 2 7

and we have to sort the spreadsheet with respect to the Kth column. Suppose K = 1 then the sorted spreadsheet will be based on the Age column.

Sr. No. Age Marks Height Weight Roll No. class
3 8 10 160 45 2 7
1 10 12 170 40 3 8
2 12 12 180 50 1 9

Input Format

Output Format

Constraints

Note: K is indexed from 0 to M-1 i.e. the first column is indexed as 0.

Sample Output

7 1 0
10 2 5
6 5 9
9 9 9
1 23 12

Athlete Sort HackerRank Solution in Python

Explanation of Solution

The athlete_sort() the function takes four arguments: the list of athletes arr, the number of athletes n, the number of attributes m, and the kth attribute k.

The function first sorts the list arr based on the kth attribute using the lambda function. In the lambda function, we are passing the kth attribute as the key to sort the list.

Finally, the function prints the sorted list arr.

The main() function is responsible for getting the input from the user and calling the athlete_sort() function. The function first gets the number of athletes n and the number of attributes m from the user. Then, it creates an empty list arr to store the athlete data.

The function then reads the athlete data into the list arr. Finally, it calls the athlete_sort() function to sort the athlete data and print the result.

After sorting the spreadsheet we have to print the sorted spreadsheet. The output of the above spreadsheet will be in the console as

Time Complexity of the Solution

Test Case of Athlete solution

Athlete Sort - HackerRank Solution in Python - Test Case - 01