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

Python仅单实现的test_balanced函数为何可同时接收字符串和列表参数?

from itertools import combinations # 原代码隐含依赖的导入

def test_balanced(s):
    # Check the parentheses in the given string are balanced
    count = 0
    for c in s:
        if c == '(':
            count += 1
        elif c == ')':
            if count == 0:
                # Close before open
                return False
            count -= 1
    # Check all open have been closed
    return count == 0

def remove_odd_brackets(s):
    if test_balanced(s):
        return {s}
    
    # Find positions of opening and closing parentheses
    os = [i for i, c in enumerate(s) if c == '(']
    cs = [i for i, c in enumerate(s) if c == ')']
    
    # Progressively remove more parentheses until we find valid solution(s)
    for n in range(1, len(os + cs)):
        result = []
        for c in combinations(sorted(os + cs), n):
            test = [ch for i, ch in enumerate(s) if i not in c]
            if test_balanced(test):
                result.append(''.join(test))
        if result:
            return set(result)
    return {''.join(c for c in s if c not in '()')} 

结论

这不属于函数重载的特殊情况,Python原生不支持基于参数类型的传统函数重载。

背后的处理逻辑

  • Python是动态类型语言,定义函数时不会对参数做强制类型约束,test_balanced的s参数可以接收任意类型的输入,只要执行过程中用到的操作该类型支持就不会报错。
  • 本例中test_balanced对s只做了两类操作:迭代遍历元素、判断单个元素是否为括号。而Python的字符串、字符列表都属于可迭代序列类型,遍历后得到的元素都是单个字符,==比较的逻辑完全一致,因此传入两种类型都能正常运行,这是Python鸭子类型特性的典型体现。
  • Python中如果定义多个同名函数,后定义的版本会直接覆盖先定义的版本,不会像C++、Java这类静态语言一样保留多个重载版本做参数匹配分发,因此不存在重载的实现基础。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 08:36:04