Athlete Sort

Sort by

recency

|

532 Discussions

|

  • + 0 comments

    I am learning lambda expression... This is very powerful. I start to understand the logic that we can sort a list depending of one of his attribute, but we have to give the index of this attribute into the lambda expression. Here my code :

    import math
    import os
    import random
    import re
    import sys
    
    
    
    if __name__ == '__main__':
        first_multiple_input = input().rstrip().split()
    
        n = int(first_multiple_input[0])
    
        m = int(first_multiple_input[1])
    
        arr = []
    
        for _ in range(n):
            arr.append(list(map(int, input().rstrip().split())))
    
        k = int(input().strip())
        
        # With lambda, we can sort depending of one attribute. If I add "-" I have descending order. Here we want ascending order.
        key = lambda item: (item[k])
        #print(sorted(arr, key=key))
        arr = sorted(arr, key=key)
        
        for sublist in arr:
            print(' '.join(map(str, sublist)))
    
  • + 0 comments
    import math
    import os
    import random
    import re
    import sys
    
    
    
    if __name__ == '__main__':
        nm = input().split()
    
        n = int(nm[0])
    
        m = int(nm[1])
    
        arr = []
    
        for _ in range(n):
            arr.append(list(map(int, input().rstrip().split())))
    
        k = int(input())
    
        arr_with_key =  [(row[k], idx, row) for idx, row in enumerate(arr)]
      
        arr_with_key.sort()
    
        for _, _, row in arr_with_key:
            print(' '.join(map(str, row)))
    
  • + 0 comments

    Here is HackerRank Athlete Sort in Python solution - https://programmingoneonone.com/hackerrank-athlete-sort-problem-solution-in-python.html

  • + 0 comments
    def set_indexer(i, arr_list):
        index_dict = {}
    
        for arr in arr_list:
            if arr[i] in index_dict.keys():
                index_dict[arr[i]].append(arr)
    
            else:
                index_dict[arr[i]] = [arr]
    
        return index_dict
    
    
    def sort_and_return(indexed_dict):
        sorted_list = sorted(indexed_dict.keys())
        sorted_arr = []
        for key in sorted_list:
            sorted_arr.extend(indexed_dict[key])
    
        return sorted_arr
    
    
    
    if __name__ == '__main__':
        nm = input().split()
    
        n = int(nm[0])
    
        m = int(nm[1])
    
        arr = []
    
        for _ in range(n):
            arr.append(list(map(int, input().rstrip().split())))
    
        k = int(input())
        
        f_arr = sort_and_return(set_indexer(k, arr))
        
        for arr in f_arr:
            for _ in arr:
                print(_, end=' ')
            print()
    
  • + 0 comments
    sorted_athletes = sorted(arr, key= lambda x: x[k])
        [print(*athlete) for athlete in sorted_athletes]