ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 프로그래머스 / 숫자 짝꿍
    코딩 테스트/Level 1 2022. 10. 27. 23:13
    반응형

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

     

    파이썬

    억지스럽게... 

    from collections import Counter
    solution = lambda num1, num2: ('0' if (result := ''.join(each * inter_n[each] for each in sorted(inter_n, reverse=True)))[0] == '0' else result) if (inter_n := Counter(list(num1)) & Counter(list(num2))) else "-1"

    덜 억지스럽게...

    from collections import Counter
    
    
    def solution(num1, num2):
        return ('0' if (result := ''.join(each * inter_n[each] for each in sorted(inter_n, reverse=True)))[
                           0] == '0' else result) if (inter_n := Counter(list(num1)) & Counter(list(num2))) else "-1"

    & 연산자로 교집합의 원소 수까지 처리되는 것을 볼 수 있다.  

    print(Counter(tuple(n1)), Counter(tuple(n2)), Counter(tuple(n1)) & Counter(tuple(n2)))
    # Counter({'1': 2, '2': 2, '3': 1}) Counter({'4': 1, '2': 1, '5': 1, '3': 1, '1': 1}) Counter({'1': 1, '2': 1, '3': 1})

     

    from collections import Counter
    
    
    def solution(n1, n2):
        inter_n = Counter(tuple(n1)) & Counter(tuple(n2))
        if inter_n:
            result = ''.join(each * inter_n[each] for each in sorted(inter_n, reverse=True))
            return '0' if result[0] == '0' else result
        else:
            return '-1'

     

    코틀린

    코틀린에서는 Comparator.reverseOrder()으로 역순 정렬이 가능합니다. 
    buildString은 내부적으로 StringBuilder를 생성하고, toString()을 자동호출 합니다.

    import kotlin.math.min
    
    class Solution {
        fun solution(x: String, y: String): String {
            val xMap = x.groupBy { it }.map { it.key to it.value.size }.toMap()
            val yMap = y.groupBy { it }.map { it.key to it.value.size }.toMap()
            val answer = buildString {
                xMap.keys.intersect(yMap.keys)
                    .associateWith { min(xMap[it]!!, yMap[it]!!) }
                    .toSortedMap(Comparator.reverseOrder())
                    .map { (key, value) ->
                        repeat(value) {
                            append(key)
                        }
                    }
            }
            return when {
                answer == "" -> "-1"
                answer[0] == '0' -> "0"
                else -> answer
            }
        }
    }
    반응형
Designed by Tistory.