首页 > 试题广场 >

配置文件恢复

[编程题]配置文件恢复
  • 热度指数:112341 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

有6条配置命令,它们执行的结果分别是:

命   令 执   行
reset reset what
reset board board fault
board add where to add
board delete no board at all
reboot backplane impossible
backplane abort install first
he he unknown command

注意:he he不是命令。

为了简化输入,方便用户,以“最短唯一匹配原则”匹配(注:需从首字母开始进行匹配):

1、若只输入一字串,则只匹配一个关键字的命令行。例如输入:r,根据该规则,匹配命令reset,执行结果为:reset what;输入:res,根据该规则,匹配命令reset,执行结果为:reset what;
2、若只输入一字串,但匹配命令有两个关键字,则匹配失败。例如输入:reb,可以找到命令reboot backpalne,但是该命令有两个关键词,所有匹配失败,执行结果为:unknown command

3、若输入两字串,则先匹配第一关键字,如果有匹配,继续匹配第二关键字,如果仍不唯一,匹配失败。
例如输入:r b,找到匹配命令reset board 和 reboot backplane,执行结果为:unknown command。
例如输入:b a,无法确定是命令board add还是backplane abort,匹配失败。

4、若输入两字串,则先匹配第一关键字,如果有匹配,继续匹配第二关键字,如果唯一,匹配成功。例如输入:bo a,确定是命令board add,匹配成功。
5、若输入两字串,第一关键字匹配成功,则匹配第二关键字,若无匹配,失败。例如输入:b addr,无法匹配到相应的命令,所以执行结果为:unknow command。
6、若匹配失败,打印“unknown command”

注意:有多组输入。
数据范围:数据组数:,字符串长度
进阶:时间复杂度:,空间复杂度:

输入描述:

多行字符串,每行字符串一条命令



输出描述:

执行结果,每条命令输出一行

示例1

输入

reset
reset board
board add
board delet
reboot backplane
backplane abort

输出

reset what
board fault
where to add
no board at all
impossible
install first
还没看完输入简化规则,居然提交过了。。。。。
s={'reset':'reset what','reset board':'board fault','board add':'where to add','board delete':'no board at all','reboot backplane':'impossible','backplane abort':'install first','board delete':'no board at all'}
while True:
    try:
        a=input()
        if a in s.keys():
            print(s[a])
        else:
            print('unknown command')
    except:
        break

发表于 2021-06-26 13:29:12 回复(1)
#先定义好命令和执行字符串
#单个命令和两个命令分开
#两个关键字的命令直接按数组存好,避免遍历的时候字符串拆分
com_One = 'reset'
com_Two = [['reset', 'board'], ['board', 'add'], ['board', 'delete'], 
           ['reboot', 'backplane'], ['backplane', 'abort']]
com_Two_Str = ['board fault','where to add','no board at all','impossible','install first']

while True:
    try:
        comstrs = input().split()
        comA = comstrs[0]
        #两个命令
        if len(comstrs) > 1:
            comB = comstrs[1]
            matchIndexs = []
            for i in range(len(com_Two)):
                if comA in com_Two[i][0]:
                    matchIndexs.append(i)
            #先在第一个关键字里找,找到匹配的,保存在matchIndexs
            if len(matchIndexs) == 0:
                print("unknown command")
            elif len(matchIndexs) == 1:
                index = matchIndexs[0]
                print(com_Two_Str[index])
            else:
            #第一个关键字不唯一,需要在第二个关键字里找
                matchIndexTwos = []
                for i in matchIndexs:
                    if comB in com_Two[i][1]:
                        matchIndexTwos.append(i)
                if len(matchIndexs) == 0:
                    print("unknown command")
                elif len(matchIndexTwos) == 1:
                    index = matchIndexTwos[0]
                    print(com_Two_Str[index])
                else:
                    print("unknown command")
                    
        #一个命令,在'reset'能找到,就输出'reset what'
        else:
            if comA in com_One:
                print("reset what")
            else:
                print("unknown command")
    except:break
        
        
 #解题思路已经在注释里了
        
    
    
    
    
    
    
发表于 2021-06-22 21:14:49 回复(0)
import sys

default_commands=["reset","reset board","board add",\
                  "board delete","reboot backplane",\
                 "backplane abort"]
default_executions=["reset what","board fault","where to add",\
                   "no board at all","impossible","install first"]
warning="unknown command"

test_case=[]
for line in sys.stdin:
    str=line.strip("\n")
    test_case.append(str)

for str in test_case:
    if str.count(" ")==0:
        if str in default_commands:
            print(default_executions[0])
        else:
            print(warning)
    elif str.count(" ")==1:
        if str not in default_commands[1::]:
            print(warning)
        else:
            a,b=str.split(" ")
            flag=0
            for i in default_commands[1::]:
                c,d=i.split(" ")
                flag=flag+1
                if a in c and b in d:
                    print(default_executions[flag])
    else:
        print(warning)
初学者第一次自己做出来的题……
发表于 2021-05-28 23:28:08 回复(0)
while True:
    try:
        x=['reset board','board add','board delete','reboot backplane','backplane abort','he he']
        x1=['board fault','where to add','no board at all','impossible','install first','unknown command']
        dic={}
        for j in range(len(x)):
                dic[x[j]]=x1[j]
        s=list(input().split())
        if len(s)==1:
            if s[0] in "reset":
                print("reset what")
            else:
                print("unknow command")
        else:
            a=[]
            for i in dic.keys():
                # i=list(",".join(i))
                    if s[0] in i and s[1] in i:
                        a.append(i)
                        if len(a)>1:
                            print("unknow command")
                        
                        else:
                            print(dic[i])
                
    except:
        break
发表于 2021-05-25 11:16:59 回复(0)
import sys
import re


lst_in = ["reset",
          "reset board", 
          "board add", 
          "board delete", 
          "reboot backplane", 
          "backplane abort"
       ]
lst_out = ["reset what", 
           "board fault", 
           "where to add", 
           "no board at all", 
           "impossible", 
           "install first", 
           "unknown command"
       ]


def func2(reg):
    # 匹配的记录
    fd = 0
    # 找到的命令
    cmd = lst_out[-1]
    for i in range(len(lst_in)):
        if re.findall(reg, lst_in[i]):
            fd += 1
            cmd = lst_out[i]
            if cmd == lst_out[0]:
                return cmd
#             print('cmd:' + cmd)
    if fd != 1:
        return lst_out[-1]
    else:
        return cmd


def func(lst):
    found = 0
    if len(lst) >= 3:
        return lst_out[-1]
    elif len(lst) == 1:
        reg = '^{}.*$'.format(lst[0])
        return func2(reg) 
    elif len(lst) == 2:
        reg = '^{}.*\s{}.*$'.format(lst[0], lst[1])
#         print(reg)
        return func2(reg)
    else:
        return []


for line in sys.stdin:
    lst = line.strip().split()
    if lst:
        print(func(lst))
    
    
        

发表于 2021-05-01 11:02:36 回复(0)

python

题目有个坑,except不能像其他题目一样用except EOFError。
输入的结束不是EOFError类型的。

dic = {"reset":"reset what", "reset board":"board fault", "board add":"where to add", 
      "board delete":"no board at all", "reboot backplane":"impossible", "backplane abort":"install first"}
dic1 = ["reset", "board", "reboot", "backplane"]
dic2 = ["board", "add", "delete", "backplane", "abort"]
while True:
    try:
        c = input().split()
        f1 = 0
        f2 = 0
        s1 = ""
        s2 = ""
        if len(c) == 1:
            if c[0] in "reset":
                print("reset what")
                continue
            else:
                print("unknown command")
                continue
        for i in dic1:
            if c[0] in i:
                f1 += 1
                s1 = i
        for i in dic2:
            if c[1] in i:
                f2 += 1
                s2 = i
        if f1 == 1 and f2 == 1:
            print(dic[" ".join([s1,s2])])
        else:
            print("unknown command")
    except:
        break
发表于 2021-04-12 21:20:20 回复(0)
题目中说:
5、若输入两字串,第一关键字匹配成功,则匹配第二关键字,若无匹配,失败。例如输入:bo a,确定是命令board add,匹配成功。
但是通过的代码中还有输入bo a 输出却是unknown command,是我理解的有问题吗?
发表于 2021-03-18 13:37:32 回复(0)
while True:
    try:
        list1=input().split()
        n=1
        list2=[['reset','board'],['board','add'],['board','delete'],['reboot','backplane'],['backplane','abort']]
        dict1={0:'board fault',1:'where to add',2:'no board at all',3:'impossible',4:'install first'}
        if len(list1)==1:
            if 'reset'.startswith(list1[0]):
                print('reset what')
            else:
                print('unknown command')
        else:
            for i in range(5):
                if list2[i][0].startswith(list1[0]) and list2[i][1].startswith(list1[1]):
                    print(dict1[i])
                    n=0
            if n:
                print('unknown command')
    except:
        break
发表于 2021-03-15 15:23:42 回复(0)
def merge_string(string):
    list_merge = []
    for i in range(len(string)):
        list_merge.append(string[:i+1])
    return list_merge
reset_list = merge_string('reset')
board_list = merge_string('board')
add_list = merge_string('add')
delete_list = merge_string('delete')
reboot_list = merge_string('reboot')
backplane_list = merge_string('backplane')
abort_list = merge_string('abort')
while True:
    try:
        string = input().split()
        if len(string)==1:
            if string[0] in reset_list:
                result = 'reset what'
            else:
                result = 'unknown command'
        else:
            if string[0] in reset_list:
                if string[0] not in reboot_list:
                    if string[1] in board_list:
                        result = 'board fault'
                    else:
                        result = 'unknown command'
                else:
                    if string[1] in board_list:
                        if string[1] not in backplane_list:
                            result = 'board fault'
                        else:
                            result = 'unknown command'
                    else:
                        if string[1] in backplane_list:
                            result = 'impossible'
                        else:
                            result = 'unknown command'
            elif string[0] in reboot_list:
                if string[1] in backplane_list:
                    result = 'impossible'
                else:
                    result = 'unknown command'
            elif string[0] in backplane_list:
                if string[0] !='b':
                    if string[1] in abort_list:
                        result = 'install first'
                    else:
                        result = 'unknown command'
                else:
                    if string[1]=='a':
                        result = 'unknown command'
                    elif string[1] in abort_list:
                        result = 'install first'
            elif string[0] in board_list:
                if string[1] in add_list:
                    result = 'where to add'
                elif string[1] in delete_list:
                    result = 'no board at all'
                else:
                    result = 'unknown command'
            else:
                result = 'unknown command'

        print(result)

    except:
        break
枚举法,时间空间效率比较高
发表于 2021-03-01 17:52:47 回复(0)
while True:
    try:
        str_1 = input().split(" ")
        if str_1[0] in "reset" and len(str_1) == 1:
            print("reset what")
        elif str_1[0] in "reset" and str_1[0] in "reboot" and str_1[-1] in "board" and str_1[-1] in "backplane":
            print("unknown command")
        elif str_1[0] in "reset" and str_1[-1] in "board":
            print("board fault")
        elif str_1[0] in "board" and str_1[0] in "backplane" and str_1[-1] in "add" and str_1[-1] in "abort":
            print("unknown command")
        elif str_1[0] in "board" and str_1[-1] in "add":
            print("where to add")
        elif str_1[0] in "board" and str_1[-1] in "delete":
            print("no board at all")
        elif str_1[0] in "reboot" and str_1[-1] in "backplane":
            print("impossible")
        elif str_1[0] in "backplane" and str_1[-1] in "abort":
            print("install first")
        else:
            print("unknown command")
    except:
        break

发表于 2021-01-31 23:55:13 回复(0)
字符串切片写法
dct ={"reset":"reset what",
"reset board":"board fault",
"board add":"where to add",
"board delete":"no board at all",
"reboot backplane":"impossible",
"backplane abort":"install first",
"he he":"unknown command"}
while True:
    try:
        a = input()
        l1 = a.split()
        num = 0
        s1 = ""
        for key,value in dct.items():
            s = key.find(" ")
            if len(l1)>2 or len(l1)<1:
                print(dct["he he"])
            elif len(l1)==1:
                if s == -1:
                    if l1[0] == key[:len(l1[0])]:
                        num+=1
                        s1 = value
            elif len(l1) == 2:
                if s != -1:
                    if l1[0] == key[:s][:len(l1[0])] and l1[1] == key[s+1:][:len(l1[1])]:
                        num+=1
                        s1 = value
        if num == 1:
            print(s1)
        else:
            print(dct["he he"])
    except:
        break
发表于 2021-01-20 11:32:56 回复(0)
dic = {'reset': 'reset what',
       'reset board': 'board fault',
       'board add': 'where to add',
       'board delete': 'no board at all',
       'reboot backplane': 'impossible',
       'backplane abort': 'install first'}
while True:
    try:
        com = input().strip()
        # 若输入的命令是完整命令,则直接输出执行结果
        if com in dic:
            print(dic[com])
        else:  # 输入的是命令的简化形式
            simcom_list = com.split(' ')
            if len(simcom_list) == 1:  # 输入的是一字串,只能匹配一个关键字的命令(本题的:reset命令)
                if 'reset'.startswith(simcom_list[0]):
                    print("reset what")
                else:
                    print("unknown command")
            elif len(simcom_list) == 2:  # 输入的是两字串,只能匹配两个关键字的命令
                match = []  # 用于存放可以匹配的完整命令
                for k in dic:  # 字典迭代取出的是键,即为完整命令
                    if ' ' in k:  # 排除掉一个关键字的命令
                        totalcom_list = k.split(' ')
                        # 若匹配成功第一个关键字,且匹配成功第二个关键字
                        if totalcom_list[0].startswith(simcom_list[0]) and totalcom_list[1].startswith(simcom_list[1]):
                            match.append(k)
                if len(match) == 1:
                    print(dic[match[0]])
                else:
                    print("unknown command")
            else:  # 输入的是三字串或者更多字串
                print("unknown command")
    except:
        break

发表于 2021-01-05 20:46:10 回复(0)
python 写的。。小白一枚。反正是跑通了。写了一个多小时。。来回搜来回做。希望指出问题,谢谢。
# 定义命令字典
command_dic={
    "reset":"reset what",
    "reset board":"board fault",
    "board add":"where to add",
    "board delete":"no board at all",
    "reboot backplane":"impossible",
    "backplane abort":"install first",
}
# 定义找不到的错误
not_found='unknown command'
# 定义一个递归函数,判断每个位置是否包含。。递归刚学写的很渣。。。
def ccc(a,b,c):
    if c == 0 and a[c].startswith(b[c]):
        return True
    elif a[c].startswith(b[c]):
        return ccc(a,b,c-1)
    return False


while True:
    try:
        # 定义一个临时字典
        tmp_list=[]
        # 讲input参数转为list,并获取参数长度
        a_list=input().split()
        a_len=len(a_list)
        # 遍历字典
        for k,v in command_dic.items():
            # 将字典key转为list 并获取长度
            cmd_list=k.split()
            cmd_len=len(cmd_list)
            # 判断输入的参数长度和字典长度是否一致,不一致就跳过
            if a_len == cmd_len:
                #将命令列表和input列表传入到函数进行判断
                if ccc(cmd_list, a_list, a_len - 1):
                    #如果返回真就将执行结果添加到临时字典
                    tmp_list.append(v)
        # 判断临时字典是否有且有一个值
        if len(tmp_list) == 1:
            print(tmp_list[0])
        else:
            print(not_found)
    except:
        break


发表于 2020-12-26 21:27:37 回复(0)
比较笨的办法,按条件跑了一下测试,不知道案例全不全(反正通过代码第一名肯定是错的)

while True:
    try:
        s = input()
        # s只有一字串
        if ' ' not in s:
            if 'reset'.startswith(s):
                print('reset what')
            else:
                print('unknown command')
        else:
            s_1, s_2 = s.split()
            flag_1 = False
            flag_2 = False
            flag_3 = False
            flag_4 = False
            flag_5 = False
            if 'reset'.startswith(s_1) and 'board'.startswith(s_2):
                flag_1 = True
            if 'reboot'.startswith(s_1) and 'backplane'.startswith(s_2):
                flag_2 = True
            if 'board'.startswith(s_1) and 'add'.startswith(s_2):
                flag_3 = True
            if 'board'.startswith(s_1) and 'delete'.startswith(s_2):
                flag_4 = True
            if 'backplane'.startswith(s_1) and 'abort'.startswith(s_2):
                flag_5 = True

            # 不唯一匹配返回unknown

            if flag_1 and (not flag_2):
                print('board fault')
            if (not flag_1) and flag_2:
                print('impossible')
            if flag_1 and flag_2:
                print('unknown command')
            if flag_3 and (not flag_4) and (not flag_5):
                print('where to add')
            if flag_4 and (not flag_3) and (not flag_5):
                print('no board at all')
            if flag_5 and (not flag_3) and (not flag_4):
                print('install first')
            if flag_3 and flag_5:
                print('unknown command')
            if (not flag_1) and (not flag_2) and (not flag_3) and (not flag_4) and (not flag_5):
                print('unknown command')
    except:
        break
发表于 2020-12-15 18:01:42 回复(0)
# 2020年11月14日12:30:39
# 定义命令字典
command_one_key = {
    "reset":"reset what",
}
command_two_key = {
    "reset board":"board fault",
    "board add":"where to add",
    "board delete":"no board at all",
    "reboot backplane":"impossible",
    "backplane abort":"install first",
}
# 根据字串匹配配置命令,原则:最短唯一匹配
def config(strs):
#   匹配结果:result,匹配结果命令长度:command_len
    result = []
    command_len = []
    if len(strs) == 1:
#       只匹配有一个关键字的命令行
        for key in command_one_key.keys():
            if strs[0] in key[0:len(strs[0])]:
                result.append(key)
                command_len.append(len(key))
#           匹配失败,不存在或不唯一
            if len(result) != 1:
                return "unknown command"
#           匹配成功
            else:
                idx = command_len.index(min(command_len))
                command = result[idx]
                return command_one_key[command]
    elif len(strs) == 2:
#       匹配有两个关键字的命令行
#       先匹配第一个关键字      
        for key in command_two_key.keys():
            if strs[0] in key.split()[0][0:len(strs[0])]:
                result.append(key)
                command_len.append(len(key))
#       第一个关键字匹配失败
        if len(result) < 1:
            return "unknown command"
#       匹配第一个关键字成功
        else:
#           匹配第二个关键字
            result2 = []
            command_len2 = []
            for i in range(len(result)):
                key2 = result[i].split()[1][0:len(strs[1])]
                if strs[1] in key2:
                    result2.append(result[i])
                    command_len2.append(command_len[i])
#           第二个关键字匹配失败
            if len(result2) != 1:
                return "unknown command"
#           第二个关键字匹配成功
            else:
                idx = command_len2.index(min(command_len2))
                command = result2[idx]
                return command_two_key[command]


while True:
    try:
        strs = input().split()
        print(config(strs))
    except:
        break
        


编辑于 2020-11-14 14:48:47 回复(0)
import re
cmd_list = ['reset', 'reset board', 'board add', 'board delete','reboot backplane', 'backplane abort'] # len = 6
do_list = ['reset what', 'board fault', 'where to add', 'no board at all','impossible', 'install first', 'unkown command'] # len = 7
        
while 1:
    try:
        flag=0
        do=''
        cmd=input().split(' ')
        l=len(cmd)
        if l==1:
            for i in filter(lambda x: x.count(' ')==0,cmd_list):
                if re.match(cmd[0], i):
                    flag +=1
                    do=do_list[cmd_list.index(i)]
            if flag ==1:
                print(do)
            else:
                print(do_list[6])
        if l==2:
            sublist=[]
            for i in filter(lambda x: x.count(' ')==1,cmd_list):
                if re.match(cmd[0], i.split(' ')[0]):
                    sublist.append(i)
            for j in sublist:
#                 print(j.split(' ')[1])
                if re.match(cmd[1],j.split(' ')[1]):
                    flag+= 1
                    do=do_list[cmd_list.index(j)]
#                     print(sublist.index(j),do_list[cmd_list.index(j)],j)
            if flag ==1:
                print(do)
            else:
                print(do_list[6])
    except:
        break

不知道为什么不通过,本地测试正常,自测调试也正常
编辑于 2020-10-22 23:48:41 回复(0)
适应扩展的情况,比如提供多个单一字符串的命令时,代码同样适用。
while True:
    try:
        command = input().split()
        dic1 = {'reset':'reset what', 'unk':'unknown command'}
        dic2 = {'reset board':'board fault', 'board add':'where to add', 
               'board delete':'no board at all', 'reboot backplane':'impossible', 
               'backplane abort':'install first'}
        if len(command) is 1:
            tag = False
            for k in dic1.keys():
                if command[0] == k[:len(command[0])]:
                    print(dic1[k])
                    tag = True
            if not tag:
                print(dic1['unk'])
        elif len(command) is 2:
            tag = False
            for k in dic2.keys():
                if command[0] == k[:len(command[0])] and command[1] == k.split()[1][:len(command[1])]:
                    print(dic2[k])
                    tag = True
            if not tag:
                print(dic1['unk'])
        else:
            print(dic1['unk'])
    except EOFError:
        break


发表于 2020-10-01 14:22:45 回复(1)
import re
cmd = ('reset', 'reset board', 'board add', 'board delete', 'reboot backplane', 'backplane abort')
res = ('reset what', 'board fault', 'where to add', 'no board at all', 'impossible', 'install first', 'unknown command')
while True:
    try:
        s = input().strip().split()
        match1_cmd = [] # 第一个关键字 匹配到的
        for j, v in enumerate(cmd):
            if re.match(s[0], v):   # 匹配以该关键字开头的
                if len(s) == 1 and len(v.split()) == 1:
                    match1_cmd.append((cmd[j], res[j]))
                elif len(s) == 2 and len(v.split()) ==2:
                    match1_cmd.append((cmd[j], res[j]))
        if len(s) == 1:
            if len(match1_cmd) == 1:
                print(match1_cmd[0][1])
            else:
                print(res[-1])
        else:
            match2_cmd = [] # 如果关键字 长度为2 继续匹配后一个管关键字
            for i in match1_cmd:
                if re.match(s[1], i[0].split()[1]):
                    match2_cmd.append(i)
            if len(match2_cmd) == 1:
                print(match2_cmd[0][1])
            else:
                print(res[-1])
    except:
        break
        

发表于 2020-09-29 23:18:10 回复(0)
栈的思想以及正则表达式匹配:
# 栈: 栈里仅有一个元素,则输出相应元素,若大于或小于一个元素,则失败
# 正则表达式 re.compile('字符元素').search('原来的字符串')
import re
import sys
for line in sys.stdin:
    n = [i for i in line.strip().split()]
    tmp = []
    if len(n)== 1:
        if re.compile(n[0]).search('reset'):
            tmp.append('reset what')
    elif len(n)== 2:
        if re.compile(n[0]).search('reset') and re.compile(n[1]).search('board') :
            tmp.append('board fault')
        if re.compile(n[0]).search('board') and re.compile(n[1]).search('add') :
            tmp.append('where to add')
        if re.compile(n[0]).search('board') and re.compile(n[1]).search('delete') :
            tmp.append('no board at all')   
        if re.compile(n[0]).search('reboot') and re.compile(n[1]).search('backplane') :
            tmp.append('impossible')   
        if re.compile(n[0]).search('backplane') and re.compile(n[1]).search('abort') :
            tmp.append('install first')       
    else:
        tmp.append('unknown command')
    # 输出
    if len(tmp) == 1:
        print(tmp[0])
    else:
        print('unknown command')


发表于 2020-09-22 15:59:19 回复(0)
import re
while True:
    try:
        list0 = []
        list0.append(['reset','reset what'])
        list0.append(['reset','board','board fault'])        
        list0.append(['board','add','where to add'])
        list0.append(['board','delete','no board at all'])
        list0.append(['reboot','backplane','impossible'])
        list0.append(['backplane','abort','install first'])
        listin = input().strip().split()
        t = 0
        if len(listin) == 1:
            if re.match(listin[0],list0[0][0]) == None:
                print('unknown command')
                continue
            else:
                print(list0[0][1])
                continue
        elif len(listin) == 2:
            t = 0
            for i in range(1,6):
                if (re.match(listin[0],list0[i][0]) != None) & (re.match(listin[1],list0[i][1]) != None):
                    if t == 0:
                        t = i                            
                    else:
                        print('unknown command')
                        continue
            if t == 0:
                print('unknown command')
                continue
            else:
                print(list0[t][2])
        elif len(listin) > 2:
            print('unknown command')
    except:
        break
发表于 2020-09-13 23:13:40 回复(0)