You are given a list of items
, where each items[i] = [type_i, color_i, name_i]
describes the type, color, and name of the i-th
item. You are also given a ruleKey
and a ruleValue
.
You need to return the number of items that match the given rule. The rule is defined as follows:
ruleKey
is "type"
, then you need to match ruleValue
with the type_i
of the items.ruleKey
is "color"
, then you need to match ruleValue
with the color_i
of the items.ruleKey
is "name"
, then you need to match ruleValue
with the name_i
of the items.Input:
items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]]
ruleKey = "color"
ruleValue = "silver"
Output:
1
Input:
items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]]
ruleKey = "type"
ruleValue = "phone"
Output:
2
items
list?
ruleKey
always among type
, color
, name
?
items
will have three components - type, color, name
?
With these clarifications, we can proceed to solve the problem.
ruleKey
to the corresponding index: “type” -> 0, “color” -> 1, “name” -> 2.ruleValue
.def countMatches(items, ruleKey, ruleValue):
# Mapping `ruleKey` to their respective index in the list
key_to_index = {"type": 0, "color": 1, "name": 2}
# Determine the index to be used for comparison
index = key_to_index[ruleKey]
# Count the matching items
count = 0
for item in items:
if item[index] == ruleValue:
count += 1
return count
# Test examples
items1 = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]]
ruleKey1 = "color"
ruleValue1 = "silver"
print(countMatches(items1, ruleKey1, ruleValue1)) # Output: 1
items2 = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]]
ruleKey2 = "type"
ruleValue2 = "phone"
print(countMatches(items2, ruleKey2, ruleValue2)) # Output: 2
This approach efficiently counts the items matching the rule provided.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?