티스토리 뷰

깔끔하게 풀어보고 싶어서 클래스와 메서드를 만들어서 풀이를 해봤다.

 

# https://leetcode.com/problems/count-items-matching-a-rule/
# count-items-matching-a-rule.py

class Solution:

    def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
        class Rule:
            def __init__(self):
                self.typedict = {}
                self.colordict = {}
                self.namedict = {}
                
            def change_dic(self, key):
                if key == 'type':
                    dic = self.typedict
                if key == 'color':
                    dic = self.colordict                
                if key == 'name':
                    dic = self.namedict
                return dic   

            def insert(self, key, item):
                dic = self.change_dic(key)
                if item in dic:
                    dic[item] += 1
                else:
                    dic[item] = 1                   
        
            def find(self, k, v):
                dic = self.change_dic(k)
                return dic[v] if v in dic else 0
        

            
        rule = Rule()    
        
        for i, item in enumerate(items):
            rule.insert('type', item[0])
            rule.insert('color', item[1])
            rule.insert('name', item[2])
        return rule.find(ruleKey, ruleValue)
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함