题解 | #配置文件恢复#
配置文件恢复
https://www.nowcoder.com/practice/ca6ac6ef9538419abf6f883f7d6f6ee5
import re
while True:
try:
list2 = ["reset","reset board","board add","board delete","reboot backplane","backplane abort"]
list4 = ["reset what","board fault","where to add","no board at all","impossible","install first"]
list1 = str(input()).split(" ")#输入
execute = ""
def is_prefix(list1, list2):#对于只有一个关键字的命令行
# if ("".join(list2[0])).startswith("".join(list1)):
#从中间匹配
# pattern = re.escape("".join(list1)) # 转义特殊字符
# matches = re.search(pattern, "".join(list2[0]))#search换成findall,并且下一句改为if len(matches) > 0:也可以
# if matches:
#pattern = re.escape("".join(list1)) # 转义特殊字符
#matches = re.match(pattern, "".join(list2[0]))
#if matches:
execute = "reset what"
else:
execute = "unknown command"
return execute
def is_twoprefix(list1,list2):#对于有两个关键字的命令行
only = 0#only是判断是否有一个输入多种匹配的情况,如果大于2则unkown
for i in range(1,6):#没有0
list3 = list2[i].split(" ")#list3是一个命令
if (("".join(list3[0])).startswith("".join(list1[0]))
and ("".join(list3[1])).startswith("".join(list1[1]))):
execute = list4[i]
only += 1
if only != 1:#only == 0或only >1时
execute = "unknown command"
return execute
# 示例测试
# str1 = "res"
# str2 = "reset"
if (len(list1) == 1):
result = is_prefix(list1, list2)
else:
result = is_twoprefix(list1, list2)
print(result) # 输出:True
except:
break
方法一:使用python自带函数startswith:
方法二:使用正则表达式:re.match
注意:match,search ,findall三者的区别:
三者都是正则寻找字符,但是match只能在开头才是True;
search可以在中间,返回值是boolen。
findall也是在中间,但是返回值为匹配的列表,所以应该用if(len(返回值))>0判断。本题明显只有match符合(但是似乎答案给的例子search和findall也可以通过哈哈)
