首页 > 试题广场 >

配置文件恢复

[编程题]配置文件恢复
  • 热度指数:114605 时间限制: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


只需要知道python里面有个神器叫string.startswith()就秒了,而且这个函数还很好记
import sys
while True:
    try:
        command=input()
        if " " not in command and "reset".startswith(command):
            print("reset what")
        elif " " in command and command!="r b" and command!="b a":
            command=command.split(" ")
            #print(command)
            if "reset".startswith(command[0]) and "board".startswith(command[1]):
                print("board fault")
            elif "reboot".startswith(command[0]) and "backplane".startswith(command[1]):
                print("impossible")
            elif "board".startswith(command[0]) and "add".startswith(command[1]):
                print("where to add")
            elif "board".startswith(command[0]) and "delete".startswith(command[1]):
                print("no board at all")
            elif "backplane".startswith(command[0]) and "abort".startswith(command[1]):
                print("install first")
            else:
                print("unknown command")
        else:
            print("unknown command")
    except EOFError:
        sys.exit()

。同理还有个string.endswith()。
发表于 2025-12-13 05:58:34 回复(0)
import sys

for line in sys.stdin:
    s = line.split()
    if s[0] in "reset" and len(s)==1:
        print("reset what")
    elif len(s)==2:
        if s[0] in 're' and s[1]=='b':
            print("unknown command")
        elif s[0]=='b' and s[1]=='a':
            print("unknown command")
        elif s[0] in "reset" and s[1] in "board":
            print("board fault")
        elif s[0] in "board" and s[1] in "add":
            print("where to add")
        elif s[0] in "board" and s[1] in "delete":
            print("no board at all")
        elif s[0] in "reboot" and s[1] in "backplane":
            print("impossible")
        elif s[0] in "backplane" and s[1] in "abort":
            print("install first")
        else:
            print("unknown command")
    else:
        print("unknown command")

发表于 2025-11-28 14:24:08 回复(0)
cmds = {
    "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"
}

singles = [k for k in cmds if ' ' not in k]
doubles = [k.split() for k in cmds if ' ' in k]

while True:
    try:
        line = input()
        words = line.split()
        
        if len(words) == 1:
            input_word = words[0]
            match = [s for s in singles if s.startswith(input_word)]
            print(cmds[match[0]] if len(match) == 1 else "unknown command")
        elif len(words) == 2:
            input_word1, input_word2 = words
            match =  [cmds[' '.join(d)] for d in doubles if d[0].startswith(input_word1) and d[1].startswith(input_word2)]
            print(match[0] if len(match) == 1 else "unknown command")
        else:
            print("unknown command")
    except:
        break

发表于 2025-11-25 15:13:55 回复(0)
好代码大家看得多了,来看究极屎山代码,虽然屎但不用动脑子
把所有命令可能的缩略词全部找出来。缩略词一样的再注意一下去重就好了
import sys


def find_keys_with_value(dictionary, s):
    matching_keys = []
    for key, value_list in dictionary.items():
        if s in value_list:
            matching_keys.append(key)
    return matching_keys


command = {
    "reset": [],
    "reset board": [],
    "board add": [],
    "board delete": [],
    "reboot backplane": [],
    "backplane abort": [],
}
###reset命令的所有子集
for i in range(1, len("reset") + 1):
    substring = "reset"[:i]
    command["reset"].append(substring)
###reset board命令所有子集
for i in range(1, len("reset") + 1):
    for j in range(1, len("board") + 1):
        substring1 = "reset"[:i]
        substring2 = "board"[:j]
        command["reset board"].append(substring1 + " " + substring2)

###board add命令所有子集
for i in range(1, len("board") + 1):
    for j in range(1, len("add") + 1):
        substring1 = "board"[:i]
        substring2 = "add"[:j]
        command["board add"].append(substring1 + " " + substring2)

###board delete命令所有子集
for i in range(1, len("board") + 1):
    for j in range(1, len("delete") + 1):
        substring1 = "board"[:i]
        substring2 = "delete"[:j]
        command["board delete"].append(substring1 + " " + substring2)

###reboot backplane命令所有子集
for i in range(1, len("reboot") + 1):
    for j in range(1, len("backplane") + 1):
        substring1 = "reboot"[:i]
        substring2 = "backplane"[:j]
        command["reboot backplane"].append(substring1 + " " + substring2)
###backplane abort命令所有子集
for i in range(1, len("backplane") + 1):
    for j in range(1, len("abort") + 1):
        substring1 = "backplane"[:i]
        substring2 = "abort"[:j]
        command["backplane abort"].append(substring1 + " " + substring2)

while True:
    try:
        s = input().strip()
        if not s:  # 如果输入为空,退出循环
            break
        if s in command["reset"]:
            print("reset what")
        elif s in command["reset board"]:
            if s in command["reboot backplane"]:
                print("unknown command")
            else:
                print("board fault")
            
        elif s in command["board add"]:
            if s in command["backplane abort"]:
                print("unknown command")
            else:
                print("where to add") 

        elif s in command["board delete"]:
            print("no board at all")
        elif s in command["reboot backplane"]:
            if s in command["reset board"]:
                print("unknown command")
            else:
                print("impossible")
        elif s in command["backplane abort"]:
            if s in command["board add"]:
                print("unknown command")
            else:
                print("install first")
        else:
            print("unknown command")
    except:
        break



发表于 2025-09-11 23:43:24 回复(0)
一心想着把代码写紧凑些
import sys
order_ls = [('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')]
for line in sys.stdin:
    a = line.strip()
    a = a.split()
    match_keys = list()
    if len(a) == 1:
        match_keys = [y[1] for y in order_ls if len(y[0].split()) == 1 and a[0] == y[0].split()[0][:len(a[0])]]
    elif len(a) == 2:
        match_keys = [y[1] for y in order_ls if len(y[0].split()) == 2 and a[0] == y[0].split()[0][:len(a[0])] and a[1] in y[0].split()[1][:len(a[1])]]
    if len(match_keys) != 1:
        print('unknown command')
    else:
        print(match_keys[0])


发表于 2024-11-27 17:19:46 回复(0)
strings = [['reset', 'board'], ['board', 'add'], ['board', 'delete'], ['reboot', 'backplane'], ['backplane', 'abort']]
output = ['board fault', 'where to add', 'no board at all', 'impossible', 'install first']

def match_reset(s, reset='reset'):
    i = 0
    while i < len(s) and i < len(reset) and s[i] == reset[i]:  # 加入边界检查
        i += 1
        if i == len(s):
            return True
    return False

def match_mul(s, k):
    count = 0
    b = []
    for idx, x in enumerate(strings):  # 使用 enumerate 提前获取索引
        i = 0
        while i < len(s) and i < len(x[k]) and x[k][i] == s[i]:  # 添加索引范围检查
            i += 1
            if i == len(s):
                count += 1
                b.append(idx)  # 直接存储索引
                break

    if count == 0:
        return [-7, b]
    elif count == 1:
        return [10, b]
    elif count > 1:
        return [7, b]

while True:
    try:
        s = input()
        if ' ' in s:
            arr = s.split()
            X = match_mul(arr[0], 0)  # 缓存结果
            if X[0] == 7:
                j = match_mul(arr[1], 1)  # 缓存结果
                if j[0] == 10:
                    print(output[j[1][0]])
                elif j[0] == 7:
                    intersection = set(X[1]) & set(j[1])  # 提前计算交集
                    if len(intersection) == 0 or len(intersection) > 1:
                        print('unknown command')
                    elif len(intersection) == 1:
                        print(output[intersection.pop()])
            elif X[0] == -7:
                print('unknown command')
            elif X[0] == 10:
                print(output[X[1][0]])  # 直接使用缓存结果
        else:
            if match_reset(s):
                print('reset what')
            else:
                print('unknown command')
    except:
        break
发表于 2024-11-26 14:42:47 回复(0)

while True:
try:
comm = ['reset','reset board','board add','board delete','reboot backplane','backplane abort']
com_ex = ['reset what','board fault','where to add','no board at all','impossible','install first']

s = input().strip().split()

if len(s) < 1 or len(s) > 2:
print('unknown command')
else:
if len(s) == 1:
if comm[0].startswith(s[0]):
print(com_ex[0])
else:
print('unknown command')
else:
index = []
for i in range(1,len(comm)):
a = comm[i].split()
if a[0].startswith(s[0]) and a[1].startswith(s[1]):
index.append(i)
if len(index) !=1:
print('unknown command')
else:
print(com_ex[index[0]])

except:
break
发表于 2024-08-23 17:49:07 回复(0)
while True:
    try:
        com_str = input().strip().split()
        key = ["reset", "reset board", "board add", "board delete", "reboot backplane", "backplane abort"]
        value = ["reset what", "board fault", "where to add", "no board at all", "impossible", "install first"]
        if len(com_str) < 1&nbs***bsp;len(com_str) > 2:
            print("unknown command")
        elif len(com_str) == 1:
            if com_str[0] == key[0][0:0 + len(com_str[0])]:
                print(value[0])
            else:
                print("unknown command")
        else:
            num, out = 0, ""
            for index, s in enumerate(key):
                if com_str[0] == s.split()[0][0:0 + len(com_str[0])] and com_str[1] == s.split()[1][0:0 + len(com_str[1])]:
                        num += 1
                        out = value[index]
            if num != 1:
                print("unknown command")
            else:
                print(out)
    except:
        break
为什么我这个预期输出只有一行?  求大佬们指点~ 
发表于 2024-08-19 18:00:39 回复(0)
import sys
input = sys.stdin.read
data = input().strip().split('\n')

commands = {
    "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"
}

def match(c):
    parts = c.split()

    if len(parts) == 1:
        # 只匹配一个关键字的命令
        matched = [cmd for cmd in commands 
        if cmd.startswith(parts[0]) and len(cmd.split()) == 1]
        
        if len(matched) == 1:
            return commands[matched[0]]
        else:
            return "unknown command"  
    
    elif len(parts) == 2:
        matched = [cmd for cmd in commands if cmd.startswith(parts[0])]

        if matched:
            second_matched = [cmd for cmd in matched 
            if len(cmd.split()) > 1 and cmd.split()[1].startswith(parts[1])]

            if len(second_matched) == 1:
                return commands[second_matched[0]]

            else:
                return "unknown command"
        
        else:
            return "unknown command"

    else:
        return "unknown command"

for line in data:
    print(match(line))

发表于 2024-08-14 14:59:52 回复(0)
commands = [
    "reset",
    "reset board",
    "board add",
    "board delete",
    "reboot backplane",
    "backplane abort",
]
results = [
    "reset what",
    "board fault",
    "where to add",
    "no board at all",
    "impossible",
    "install first",
]

def check(line):
    s = line.split()
    if len(s) < 1 or len(s) > 2:
        return "unknown command"
    elif len(s) == 1:
        if commands[0].startswith(s[0]):
            return results[0]
    elif len(s) == 2:
        res = []
        for i in range(1, 6):
            item_list = commands[i].split()
            if item_list[0].startswith(s[0]) and item_list[1].startswith(s[1]):
                res.append(results[i])
        if len(res) == 1:
            return res[0]
    return "unknown command"

while True:
    try:
        command = input().strip()
        print(check(command))
    except:
        break
发表于 2024-07-13 14:24:40 回复(0)
import sys
key = [['reset'],['reset','board'],['board','add'],['board','delete'],['reboot','backplane'],['backplane','abort']]
value = ['reset what','board fault','where to add','no board at all','impossible','install first']
def check(line):
    s_input = line.split()
    if len(s_input) == 1:
        if s_input[0] == str(key[0][0][:len(s_input[0])]):
            return value[0]
    elif len(s_input) == 2:
        index = []
        for i in range(1,6):
            if (s_input[0] == str(key[i][0])[:len(s_input[0])]) and (s_input[1] == str(key[i][1])[:len(s_input[1])]):
                index.append(i)
        if len(index) == 1:
            return value[index[0]]
    return 'unknown command'

for line in sys.stdin:
    print(check(line))

发表于 2024-03-30 21:08:52 回复(0)
#参考了大佬的代码
import sys
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"}
for a in sys.stdin:
    line = a.split()
    res = []
    for i in dic:
        if len(i.split()) == len(line):
            flag = "True"
            for j in range(len(line)):
                if i.split()[j].startswith(line[j]):
                    pass
                else:
                    flag = "False"
                    break
            if flag == "True":
                res.append(i)
        else:
            flag = "False"
    if len(res) == 1:
        print(dic[res[0]])
    else:
        print("unknown command")

编辑于 2024-02-16 14:02:36 回复(0)
cmd_result = {
    "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",
}


def execute_cmd(cmd: str):
    cmd_list = cmd.split()
    matched_keys = []
    if len(cmd_list) == 1:
        # 单条命令
        tmp_cmd = cmd_list[0]
        for k in cmd_result:
            if k.startswith("reset") and "reset".startswith(tmp_cmd):
                matched_keys.append(("reset", True))
                break
            if k.startswith(tmp_cmd):
                matched_keys.append((k, k.split() == 1))
    else:
        for k in cmd_result:
            if k != "reset":
                if k.startswith(cmd_list[0]):
                    matched_keys.append((k, False))
        if len(matched_keys) > 0:
            for index, k in enumerate(matched_keys):
                if k[0].split()[-1].startswith(cmd_list[1]):
                    matched_keys[index] = (k[0], True)
    matched_keys = [v for v in matched_keys if v[1]]
    if len(matched_keys) == 1:
        print(cmd_result.get(matched_keys[0][0]))
    else:
        print("unknown command")


while True:
    try:
        cmd_str = input()
        execute_cmd(cmd_str)
    except:
        break

发表于 2023-10-08 22:15:29 回复(0)
import sys
d1 = {'reset board':'board fault','board add':'where to add','board delete':'no board at all','reboot backplane':'impossible','backplane abort':'install first'}

def print_command(a:list):
    cnt = 0
    res = ''
    if len(a) == 1:
        if ''.join(a) == 'reset'[:len(a[0])]:
            print('reset what')
        else:
            print('unknown command')
    elif len(a) == 2:
        for x,y in d1.items():
            x = x.split()
            if a[0] == x[0][:len(a[0])] and a[1] == x[1][:len(a[1])]:
                res = y
                cnt+=1
        if cnt == 1:
            print(res)
        else:
            print('unknown command')
    else:
        print('unknown command')


for line in sys.stdin:
    a = line.split()
    print_command(a)
   
发表于 2023-07-01 23:12:42 回复(0)
import re
def func(us=''):
    ml_dict = {
        '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'
    }
    default_comm = 'unknown command'
    if ' ' in us:
        us_list = us.split()
        ret = [i for i in ml_dict.keys() if ' ' in i
                and re.match(us_list[0], i) and re.search(' ' + us_list[1], i)]
        if len(ret) == 1:
            print(ml_dict.get(ret[0]))
        else:
            print(default_comm)
    else:
        ret = [i for i in ml_dict.keys() if ' ' not in i and re.match(us, i)]
        if len(ret) == 1:
            print(ml_dict.get(ret[0]))
        else:
            print(default_comm)
while True:
    try:
        func(input())
    except:
        break
发表于 2023-04-20 23:49:19 回复(0)
最弱智的方法
while True:
    try:
        a=input()
        b=a.split()
        if len(b)==1:
            if a in 'reset':
                print('reset what')
            else:
                print('unknown command')
        elif len(b)==2:
            if not (b[0] in 'reset' and b[1] in 'backplane') and b[0][0]=='r' and b[1][0]=='b':
                if b[0] in 'reset' and b[1] in 'board':
                    print('board fault')
                if b[0] in 'reboot' and b[1] in 'backplane':
                    print('impossible')
            elif not (b[0]=='b' and b[1]=='a') and b[0][0]=='b' and b[1][0]=='a':
                if b[0] in 'board' and b[1] in 'add':
                    print('where to add')
                if b[0] in 'backplane' and b[1] in 'abort':
                    print('install first')
            elif b[0] in 'board' and b[1] in 'delete':
                print('no board at all')
            else:
                print('unknown command')

    except:
        break

发表于 2023-03-12 06:20:43 回复(0)
我他喵的用了半天 树,发现解决不了。。。
发表于 2023-03-04 23:35:31 回复(0)
while True:
    try:
        s = list(input().split())
        d = {'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'}
        l1 = [['reset','board'],['board','add'],['board','delete'],['reboot','backplane'],['backplane','abort']]
        if len(s) == 1:
            if s[0] == 'reset'[:len(s[0])]:
                print('reset what')
            else:
                print('unknown command')
        elif len(s) == 2:
            chr = ''
            l2 = []
            for i in l1:
                if s[0] == i[0][:len(s[0])] and s[1] == i[1][:len(s[1])]:
                    chr = i[0] + ' ' + i[1]
                    l2.append(chr)
            if len(l2)==1:
                print(d[l2[0]])
            else:
                print('unknown command')
        else:
            print('unknown command')


    except:
        break


发表于 2023-03-01 15:15:58 回复(0)

问题信息

难度:
36条回答 28863浏览

热门推荐

通过挑战的用户

查看代码
配置文件恢复