Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to count items matching a rule using Python
Suppose we have an array nums, where each nums[i] contains three elements [type_i, color_i, name_i]. These are describing the type, color, and name of the ith item. We also have a rule represented by two other strings, ruleKey and ruleValue. Now we can say the ith item matches the rule if one of the following is true ?
ruleKey = "type" and ruleValue = type_i.
ruleKey = "color" and ruleValue = color_i.
ruleKey = "name" and ruleValue = name_i.
We have to find the number of items that match the given rule.
So, if the input is like ?
| Bike | blue | ElecB |
| Car | silver | Sumo |
| Bike | blue | TVS |
And ruleKey = "color", ruleValue = "blue", then the output will be 2 as there are two matches: ["Bike","blue","ElecB"] and ["Bike","blue","TVS"].
Method 1: Using Index-Based Approach
We can solve this by mapping the ruleKey to its corresponding index and then checking each item ?
def solve(items, ruleKey, ruleValue):
count = 0
rule_index = {"type": 0, "color": 1, "name": 2}
index = rule_index[ruleKey]
for item in items:
if item[index] == ruleValue:
count += 1
return count
items = [["Bike","blue","ElecB"],["Car","silver","Sumo"],["Bike","blue","TVS"]]
ruleKey = "color"
ruleValue = "blue"
print(solve(items, ruleKey, ruleValue))
2
Method 2: Using List Comprehension
We can use list comprehension for a more concise solution ?
def solve(items, ruleKey, ruleValue):
rule_index = {"type": 0, "color": 1, "name": 2}
index = rule_index[ruleKey]
return sum(1 for item in items if item[index] == ruleValue)
items = [["Bike","blue","ElecB"],["Car","silver","Sumo"],["Bike","blue","TVS"]]
ruleKey = "type"
ruleValue = "Bike"
print(solve(items, ruleKey, ruleValue))
2
Method 3: Using Filter Function
We can also use Python's built-in filter function ?
def solve(items, ruleKey, ruleValue):
rule_index = {"type": 0, "color": 1, "name": 2}
index = rule_index[ruleKey]
matching_items = filter(lambda item: item[index] == ruleValue, items)
return len(list(matching_items))
items = [["Bike","blue","ElecB"],["Car","silver","Sumo"],["Bike","blue","TVS"]]
ruleKey = "name"
ruleValue = "ElecB"
print(solve(items, ruleKey, ruleValue))
1
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Index-Based Loop | O(n) | O(1) | Readable and efficient |
| List Comprehension | O(n) | O(1) | Concise code |
| Filter Function | O(n) | O(n) | Functional programming style |
Conclusion
Use the index-based approach for clarity and efficiency. The list comprehension method offers concise code, while the filter function provides a functional programming approach. All methods have O(n) time complexity where n is the number of items.
