Problem Solving/Programmers

[Programmers]위클리 챌린지 6주차: 복서 정렬하기(Python)/Sorting

이진2 2021. 9. 12. 13:11

https://programmers.co.kr/learn/courses/30/lessons/85002

 

코딩테스트 연습 - 6주차

복서 선수들의 몸무게 weights와, 복서 선수들의 전적을 나타내는 head2head가 매개변수로 주어집니다. 복서 선수들의 번호를 다음과 같은 순서로 정렬한 후 return 하도록 solution 함수를 완성해주세요

programmers.co.kr

파이썬의 람다를 이용해서 정렬을 간단하게 구현

파이썬의 sort함수는 C++과 다르게 기본적으로 stable sort를 지원한다

def solution(weights, head2head):
    answer = []
    result=[[0, 0, weights[i], i+1] for i in range(len(weights))]
    
    for i in range(len(head2head)):
        head=head2head[i]
        win=0
        tot=0
        
        for j in range(len(head)):
            if head[j]=='N': continue
            if head[j]=='W': 
                if weights[i]<weights[j]:
                    result[i][1]+=1
                win+=1
            tot+=1
        
        if tot!=0:
            result[i][0]=win/tot
    
    result.sort(key=lambda x: (-x[0], -x[1], -x[2], x[3]))
    return [r[3] for r in result]