[LeetCode]#1773. Count Items Matching a Rule
Environment: Python 3.8
Key technique: if
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.
The ith item is said to match the rule if one of the following is true:
ruleKey == “type” and ruleValue == typei.
ruleKey == “color” and ruleValue == colori.
ruleKey == “name” and ruleValue == namei.
Return the number of items that match the given rule.
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”].
Analysis:
- Input ruleKey and ruleValue.
- Check items.
- We can see item2 color matches ruleValue. Count =count+1.
Solution:
class Solution:
def countMatches(self, items, ruleKey, ruleValue):
count=0
for i in items:
if (ruleKey == "type" and i[0] == ruleValue):
count+=1
elif (ruleKey == "color" and i[1] == ruleValue):
count+=1
elif(ruleKey == "name" and i[2] == ruleValue):
count+= 1
return count
Submissions:
Reference:
https://leetcode.com/problems/count-items-matching-a-rule/discuss/1099333/Python-100-100