ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 99클럽(2기) - 코테스터디 20일차 TIL # Array
    Algorithm 2024. 6. 18. 09:24

    LeetCode - 1773. Count Items Matching a Rule

    You are given an array items, where each items[i] = [typei, colori, namei] describes the type, color, and name of the ith item. You are also given a rule represented by two strings, ruleKey and ruleValue.

     

    Example 1:

    Input: items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver"
    Output: 1
    Explanation: There is only one item matching the given rule, which is ["computer","silver","lenovo"].

     

    1. 나의 풀이

     이중리스트 items의 요소를 item이라고 할 때, item은 [type, color, name] 으로 구성된다. 즉, itmes = [[type1, color1, name1], [type2, color2, name2], [type3, color3, name3], ...] 이다. ruleKey로는 "type", "color", "name" 중 하나가 입력되며, 특정 item의 ruleKey에 해당하는 ruleValue를 찾으려면 ruleKey가 item에서 몇 번째 인덱스를 가리키는지 알아내야 한다.

     

    1) ruleKey별 특정 인덱스 값을 갖는 딕셔너리 생성

     모든 item은 type, color, name 순으로 구성되기 때문에 item에서 type의 인덱스는 무조건 0, color의 인덱스는 무조건 1, name의 인덱스는 무조건 2이다. item[0]은 type에 대한 정보, itme[1]은 color에 대한 정보, item[2]은 name에 대한 정보를 나타낸다. 따라서 item에서 인덱스로 접근해 ruleValue를 알아내기 위해서 type에 대한 값을 0, color에 대한 값을 1, name에 대한 값을 2로 매핑한 rule이라는 dictionary를 생성했다.

     

    2) rule[ruleKey] 값을 rule_value_idx에 할당 

     item에서 ruleValue에 접근하기 위한 rule_value_idx 변수에 rule[ruleKey] 값을 할당한다.

     

    3) 조건을 만족하는 ruleValue로 구성된 리스트의 요소 개수를 반환

     리스트 컴프리헨션으로 'item[rule_value_idx] 값이 ruleValue와 같다'는 조건을 만족하는 ruleValue들을 담는 리스트 생성한다. 그 후 해당 리스트의 요소 개수를 반환하면 끝!

    class Solution:
        def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
            rule = {
                "type": 0,
                "color": 1,
                "name": 2
            }
    
            rule_value_idx = rule[ruleKey]
    
            return len([ruleValue for item in items if item[rule_value_idx] == ruleValue])

     

     

    2. 또다른 접근

     발표하신 분이 수식과 flowchart를 활용해서 코드의 논리 구조를 파악하시는 것을 보고 나도 한번 해봐야겠다고 생각했다. 바로 한번 아래와 같이 flowchart로 함수의 논리를 도식화 해봤다. 

     

     

    3. 새롭게 알게 된 점

     flowchart를 사용하는 것이 코드의 정확성을 보장하는 좋은 방법이라는 것을 배웠다. 실무에서 비즈니스 로직 그릴 때는 써봤지만 이런 식으로 코드가 정확한지 스스로 파악할 때 써보지는 않았다. 써보니 함수의 논리 구조가 더 명확히 보이는 것 같다. 앞으로도 문제를 풀기 전 문제를 어떻게 풀 것인지 고민하는 단계에서 flowchart를 사용해보면 좋을 것 같다. 

    댓글

Designed by Tistory.