# Program to count items matching a rule using Python

PythonServer Side ProgrammingProgramming

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 is matched 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 number of matching we can find.

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 match [["Bike","blue","ElecB"] and ["Bike","blue","TVS"]].

To solve this, we will follow these steps −

• count := 0

• if ruleKey is same as "type", then

• for i in range 0 to size of items, do

• if items[i, 0] is same as ruleValue, then

• count := count + 1

• if ruleKey is same as "color", then

• for i in range 0 to size of items, do

• if items[i, 1] is same as ruleValue, then

• count := count + 1

• if ruleKey is same as "name", then

• for i in range 0 to size of items, do

• if items[i, 2] is same as ruleValue, then

• count := count + 1

• return count

Let us see the following implementation to get better understanding −

## Example

Live Demo

def solve(items, ruleKey, ruleValue):
count = 0
if ruleKey == "type":
for i in range(len(items)):
if items[i][0] == ruleValue:
count += 1
if ruleKey == "color":
for i in range(len(items)):
if items[i][1] == ruleValue:
count += 1
if ruleKey == "name":
for i in range(len(items)):
if items[i][2] == ruleValue:
count += 1
return count
items = [["Bike","blue","ElecB"],["Car","silver","Sumo"],["Bike","blue","TVS"]]
ruleKey = "color"
ruleValue = "blue"
print(solve(items, ruleKey, ruleValue))

## Input

[["Bike","blue","ElecB"],["Car","silver","Sumo"],["Bike","blue","TVS"]],"color",
"blue"

## Output

2
Updated on 29-May-2021 14:32:09