소프트웨어에 대한 모든 것

LeetCode 풀이 - 1773. Count Items Matching a Rule 본문

알고리즘/LeetCode

LeetCode 풀이 - 1773. Count Items Matching a Rule

앤테바 2021. 10. 19. 20:45
반응형

1773. Count Items Matching a Rule

문제)

솔루션1)

class Solution:
    def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
        type_dict = {}
        color_dict = {}
        name_dict ={}
        
        for item in items:            
            if item[0] in type_dict:
                type_dict[item[0]] += 1                
            else:
                type_dict[item[0]] = 1
                
            if item[1] in color_dict:
                color_dict[item[1]] += 1                
            else:
                color_dict[item[1]] = 1
                
            if item[2] in name_dict:
                name_dict[item[2]] += 1                
            else:
                name_dict[item[2]] = 1
        
        if ruleKey == "type":
            return type_dict.get(ruleValue, 0)
        elif ruleKey == "color":
            return color_dict.get(ruleValue, 0)
        else:
            return name_dict.get(ruleValue, 0)

솔루션2)

class Solution:
    def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
        key = ['type', 'color', 'name'].index(ruleKey)
        count = 0
        for item in items:
            if item[key] == ruleValue:
                count += 1
        return count

솔루션3)

class Solution:
    def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
        idx = ['type', 'color', 'name'].index(ruleKey)
        return sum(map(lambda x: x == ruleValue, [item[idx] for item in items]))
반응형
Comments