使用Python编写计算规则匹配项的程序
假设我们有一个数组nums,其中每个nums[i]包含三个元素 [type_i, color_i, name_i],分别描述第i个item的类型、颜色和名称。我们还有一个由另外两个字符串ruleKey和ruleValue表示的规则。现在,如果下列条件之一成立,则可以说第i个item匹配该规则 −
- ruleKey = “type” 且 ruleValue = type_i.
-
ruleKey = “color” 且 ruleValue = color_i.
-
ruleKey = “name” 且 ruleValue = name_i.
我们需要找到符合条件的匹配项的数量。
因此,如果输入如下:
自行车 | 蓝色 | ElecB |
---|---|---|
汽车 | 银色 | Sumo |
自行车 | 蓝色 | TVS |
且 ruleKey = “color”,ruleValue = “blue”,那么输出将为2,因为有两个匹配项[[“Bike”,”blue”,”ElecB”] 和 [“Bike”,”blue”,”TVS”]]。
为了解决这个问题,我们将采取以下步骤 –
- count := 0
-
如果ruleKey与“type”相同,则
- 对于items的0到size范围内的i,执行以下操作 –
- 如果items[i,0]与ruleValue相同,则
-
count := count + 1
- 对于items的0到size范围内的i,执行以下操作 –
-
如果ruleKey与“color”相同,则
- 对于items的0到size范围内的i,执行以下操作 –
- 如果items[i,1]与ruleValue相同,则
-
count := count + 1
- 对于items的0到size范围内的i,执行以下操作 –
-
如果ruleKey与“name”相同时,则
- 对于items的0到size范围内的i,执行以下操作 –
- 如果items[i, 2]与ruleValue相同,则
-
count := count + 1
- 对于items的0到size范围内的i,执行以下操作 –
-
返回count
现在看下面实现代码以获得更好的理解 –
示例
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))
输入
[["Bike","blue","ElecB"],["Car","silver","Sumo"],["Bike","blue","TVS"]],"color",
"blue"
输出
2