ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • OX퀴즈
    코딩 테스트/Level 0 2022. 11. 8. 16:44
    반응형

    https://school.programmers.co.kr/learn/courses/30/lessons/120907

    파이썬

    문자열의 split 메소드를 이용하자.

    q.split()은 q.split(' ')과 같다. 

    기능별로 함수를 분리했다.

    def test(q):
        temp = q.split()
        if temp[1] == '+':
            return int(temp[0]) + int(temp[2]) == int(temp[4])
        else:
            return int(temp[0]) - int(temp[2]) == int(temp[4])
    
    
    def solution(quiz):
        answer = []
        for each in quiz:
            if test(each):
                answer.append('O')
            else:
                answer.append('X')
        return answer

    if 문을 가볍게

    다른 언어에서는 3항 연산자(ternary operators)라고 한다,

    a > b ? a : b
    a가 b보다 크면 a. 아니면 b.

    파이썬에서는 이를 conditional expressions(조건 표현 ?)라고 한다. 
    a if a > b else b

    컨디셔널 익스프레션을 사용해보자. 

    def test(q):
        q = q.split()
        return int(q[0]) + int(q[2]) == int(q[4]) if q[1] == '+' else int(q[0]) - int(q[2]) == int(q[4])
    
    
    def solution(quiz):
        a = []
        for each in quiz:
            a.append('O' if test(each) else 'X')
        return a

     

    for 을 가볍게

    리스트 컴프리헨션을 사용하자.

    def test(q):
        q = q.split(' ')
        return (int(q[0]) + int(q[2]) if q[1] == '+' else int(q[0]) - int(q[2])) == int(q[4])
    
    
    def solution(quiz):
        return ['O' if test(each) else 'X' for each in quiz]

    PEP8에 탑-레벨 함수는 2줄의 여백을 두는 제안이 있다.
    Surround top-level function and class definitions with two blank lines.
    https://peps.python.org/pep-0008/#blank-lines

    'PEP'란: Python Enhancement Proposal(파이썬 개선 제안서)라는 공식 문서.
    https://wikidocs.net/21733

    'PEP8'이란 Style Guide for Python Code(파이썬 코드 스타일 가이드)
    https://peps.python.org/pep-0008/

    물론 가이드라서 굳이 지킬 필요는 없지만,
    굳이 안 지킬 필요도 없어서...

    PEP8을 암기할 필요는 없다. 
    사용중인 IDE의 코드 포매팅 기능을 쓰자. 

    vs-code: Shift + Alt + F
    pyCharm: Ctrl + Alt + L

     

    파이썬에서는 함수 내에서 함수를 선언할 수 있다.  

    물론 함수 내 함수 선언의 장점이 있지만..
    여기서는 그 장점보다는
    pep8을 지키면서 함수 사이는 1줄을 쓰고 싶어서...  

    def solution(quiz):
        def test(q):
            return (int(q[0]) + int(q[2]) if q[1] == '+' else int(q[0]) - int(q[2])) == int(q[4])
    
        return ['O' if test(each.split()) else 'X' for each in quiz]
    def solution(quiz):
        def test(q):
            return (int(q[0]) + int(q[2]) if q[1] == '+' else int(q[0]) - int(q[2])) == int(q[4])
    
        return ['O' if test(each) else 'X' for each in map(lambda x: x.split(), quiz)]
    def solution(quiz):
        return ['O' if each else 'X' for each in
                map(lambda q: ((int(q[0]) + int(q[2])) if q[1] == '+' else (int(q[0]) - int(q[2]))) == int(q[4]),
                    map(lambda x: x.split(), quiz))]
    def solution(quiz):
        return list(map(lambda each: 'O' if each else 'X',
                        map(lambda q: ((int(q[0]) + int(q[2])) if q[1] == '+' else (int(q[0]) - int(q[2]))) == int(q[4]),
                            map(lambda x: x.split(), quiz))))

    이렇게 함수형으로 한 줄 코딩이 가능하긴 하다. 하지만 가독성이....

     

    EVAL 함수

    eval 함수를 이용해도 풀수 있으나
    eval 함수는 보안 문제를 일으킬 수 있기 때문에, 현업에서는 잘 사용하지 않음.
    취업과 관련된 코테라면 사용하지 않는 것을 추천함. 

    def solution(quiz):
        return ['O' if eval(each.replace('=', '==')) else 'X' for each in quiz]

     

    코틀린

    class Solution {
        fun solution(quiz: Array<String>): List<String> {
            val answer = mutableListOf<String>()
            for (each in quiz) {
                val tokens = each.split(" ")
                if (tokens[1] == "+")
                    answer.add(if (tokens[0].toInt() + tokens[2].toInt() == tokens[4].toInt()) "O" else "X")
                else
                    answer.add(if (tokens[0].toInt() - tokens[2].toInt() == tokens[4].toInt()) "O" else "X")
            }
            return answer
        }
    }
    class Solution {
        fun solution(quiz: Array<String>) = quiz
            .map { it.split(" ") }
            .map {
                when (it[1]) {
                    "+" -> it[0].toInt() + it[2].toInt() == it[4].toInt()
                    else -> it[0].toInt() - it[2].toInt() == it[4].toInt()
                }
            }
            .map { if (it) "O" else "X" }
    }

    가독성을 생각하면 이 정도에서 멈추는 것도 좋을 것 같다. 

    class Solution {
        fun solution(quiz: Array<String>) = quiz
            .map { it.split(" ") }
            .map {
                when (it[1]) {
                    "+" -> +it[2].toInt()
                    else -> -it[2].toInt()
                } + it[0].toInt() == it[4].toInt()
            }
            .map { if (it) "O" else "X" }
    }

     

    반응형
Designed by Tistory.