Python实现:编写适配任意长度列表的函数查找所有字符串共有字符
适配任意长度字符串列表的公共字符查找实现
原代码核心问题
- 判断逻辑硬编码了
x[0]、x[1]、x[2]三个索引,仅支持长度为3的输入列表,列表长度变化时会直接报错或返回错误结果 - 遍历逻辑存在冗余,重复字符会反复覆盖结果变量,执行效率低
最优实现方案(利用集合交集特性)
Python集合内置的交集运算天然支持任意数量的集合操作,代码简洁且执行效率高:
internal_input = ["hello", "world", "python", ] def in_all_str(x): # 输入为空直接返回空集合 if not x: return set() # 取第一个字符串的字符集合作为初始基准 common_chars = set(x[0]) # 依次和后续所有字符串的字符集合求交集 for s in x[1:]: common_chars.intersection_update(set(s)) # 提前终止:交集为空时无需继续计算 if not common_chars: break return common_chars print(in_all_str(internal_input))
运行结果仍为{'o'},输入列表长度任意变化都能正常计算。
手动遍历实现版本(适合入门理解底层逻辑)
如果希望手动实现判断逻辑,可参考以下写法:
def in_all_str(x): result = set() if not x: return result # 遍历第一个字符串的去重字符作为候选 for char in set(x[0]): # 校验字符是否存在于所有字符串中 is_common = True for s in x: if char not in s: is_common = False break if is_common: result.add(char) return result
内容的提问来源于stack exchange,提问作者NeverLeave
相关产品推荐
相关产品推荐

