Python 单词接龙

B站影视 2025-02-28 15:51 2

摘要:def word_chain(k, words):# 将起始单词设定为起点start_word = words[k]used = [False] * len(words) # 用于标记单词是否已被使用used[k] = True # 标记起始单词已使用resu

def word_chain(k, words):# 将起始单词设定为起点start_word = words[k]used = [False] * len(words) # 用于标记单词是否已被使用used[k] = True # 标记起始单词已使用result = start_word # 初始的单词串def find_next_word(current_word):nonlocal resultlast_char = current_word[-1] # 获取当前单词的最后一个字母candidates = # 找到所有可以接上的单词for i in range(len(words)):if not used[i] and words[i][0] == last_char:candidates.append(words[i])if not candidates:return # 没有可以接上的单词,结束递归# 按照规则排序:首先按长度,长度相同则按字典序candidates.sort(key=lambda x: (-len(x), x))# 选择第一个候选单词next_word = candidates[0]used[words.index(next_word)] = True # 标记该单词已使用result += next_word # 将选中的单词添加到结果中# 递归调用,继续接龙find_next_word(next_word)# 从起始单词开始进行单词接龙find_next_word(start_word)return result# 输入处理k, n = map(int, input.split) # 获取起始单词索引和单词个数words = [input.strip for _ in range(n)] # 读取所有单词# 输出最终的单词串print(word_chain(k, words))输入解析:首先读取起始单词的索引,接着读取单词列表。递归或回溯搜索:从起始单词出发,查找所有符合条件的下一个单词,并继续接龙。记录每一次的接龙结果,并且在每次选择时遵循“长度最长,字典序最小”的规则。输出最终结果:返回最后得到的最长接龙串。

来源:俊楠教育

相关推荐