Count Items Matching a Rule

Here is the solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
    def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
        """
        Returns the number of items that match the given rule.
        """
        count = 0
        for item in items:
            if ruleKey == "type" and item[0] == ruleValue:
                count += 1
            elif ruleKey == "color" and item[1] == ruleValue:
                count += 1
            elif ruleKey == "name" and item[2] == ruleValue:
                count += 1
        return count

The solution works by iterating through the items, checking if each item matches the rule. The code uses the if statement to check if the rule key and value match the item. The code then increments the count if the item matches the rule. The code returns the count at the end.

This is efficient because it only needs to iterate through the items once. The solution is also easy to understand because it uses simple building blocks that are well-known and well-documented.

Here is a breakdown of the code:

  • Iterating through the items. The code iterates through the items, checking if each item matches the rule.
  • Checking if the item matches the rule. The code uses the if statement to check if the rule key and value match the item.
  • Incrementing the count if the item matches the rule. The code increments the count if the item matches the rule.
  • Returning the count at the end. The code returns the count at the end.