You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写同时返回布尔值与字符串的递归函数实现元素符号拼单词

实现方案

多返回值实现逻辑

Python原生支持函数返回多个值,只需在return语句中用逗号分隔多个返回对象即可,调用函数时可以用对应数量的变量分别接收返回值。

完整递归函数实现

def isSpelled(word, symbols, symbol_map):
    # 递归终止条件:待匹配字符为空,匹配成功
    if not word:
        return (True, "")
    
    # 优先匹配2位元素符号,避免短符号截断有效长匹配
    if len(word) >= 2:
        prefix = word[:2].lower()
        for sym in symbols:
            if sym.lower() == prefix:
                match_res, match_str = isSpelled(word[2:], symbols, symbol_map)
                if match_res:
                    return (True, sym + match_str)
    
    # 2位匹配失败,尝试匹配1位元素符号
    prefix = word[:1].lower()
    for sym in symbols:
        if sym.lower() == prefix:
            match_res, match_str = isSpelled(word[1:], symbols, symbol_map)
            if match_res:
                return (True, sym + match_str)
    
    # 无有效匹配,返回失败
    return (False, "")

调用&输出示例

# 测试示例
test_word = "silver"
match_flag, match_symbols = isSpelled(test_word.lower(), symbols, d_whole)

if match_flag:
    # 提取对应元素名称序列
    element_names = []
    idx = 0
    while idx < len(match_symbols):
        if idx + 1 < len(match_symbols) and match_symbols[idx:idx+2] in d_whole:
            element_names.append(d_whole[match_symbols[idx:idx+2]])
            idx += 2
        else:
            element_names.append(d_whole[match_symbols[idx]])
            idx += 1
    # 输出符合要求的格式
    print(f"{test_word.capitalize()} can be spelled as {match_symbols}")
    print(f"对应元素序列:{'、'.join(element_names)}")
else:
    print("无匹配的拼写方案")

关键说明

  • 递归逻辑优先匹配2位符号,避免出现类似Silver先匹配S(硫)导致后续ilver无法匹配的问题
  • 匹配阶段统一转小写做对比,输出保留元素符号原生大小写,满足示例输出格式要求
  • 函数返回的元组第一个值为代表匹配结果的布尔值,第二个值为拼接完成的符号字符串,无匹配时第二个值为空字符串

内容的提问来源于stack exchange,提问作者Zy Taga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 12:39:03