프로그래머스 Level 1(Java/Python3) 완주하지 못한 선수

박유현·2020년 7월 6일
0

코딩테스트 연습

목록 보기
2/2

https://programmers.co.kr/learn/courses/30/lessons/42576?language=python3

자바로 작성했던 코드

import java.util.Arrays;
class Solution {
    public String solution(String[] participant, String[] completion) {
        String answer = "";
        Arrays.sort(participant);
        Arrays.sort(completion);
        for(int i = 0; i < completion.length; i ++) {
            if(! participant[i].equals(completion[i])) {
                answer = participant[i];
                break;
            }
        }
        if(answer.equals("")) {
            answer = participant[participant.length - 1];
        }
        return answer;
    }
}

파이썬으로 바꿨다.

def solution(participant, completion):
    answer = ''
    participant.sort()
    completion.sort()
    for i in range(len(completion)):
        if participant[i] != completion[i]:
            answer = participant[i]
            break
    if answer == '':
        answer = participant[len(participant) - 1]
    return answer

자바와 달리 1. sort() 함수를 쓸 때 import하지 않아도 되고, 2. 선언할 때 자료형을 명시하지 않아도 되며, 3. for문이 보다 간단하다. 4. 문자열의 값을 비교할 때 ==연산자를 쓸 수 있어서 편하다.

0개의 댓글