Python实现判断两个字符串是否为变位词(anagram)的函数
变位词判断函数eh_anagrama实现
功能说明
- 接收两个字符串类型的单词作为入参,判断是否为变位词(字母组成完全一致,忽略大小写和字符顺序)
- 支持可选返回两个单词的字符出现次数字典
实现代码
from collections import Counter def eh_anagrama(word1: str, word2: str, return_count: bool = False): # 统一转为小写忽略大小写差异 word1_lower = word1.lower() word2_lower = word2.lower() # 长度不一致直接判定为非变位词 if len(word1_lower) != len(word2_lower): result = False else: count1 = Counter(word1_lower) count2 = Counter(word2_lower) result = count1 == count2 # 按参数决定是否返回统计字典 if return_count: return result, dict(count1), dict(count2) return result
测试用例验证
>>> eh_anagrama('caso', 'SaCo') True >>> eh_anagrama('caso', 'casos') False
如果需要获取字符统计结果,传参return_count=True即可,返回值结构为(是否为变位词, 第一个单词的字符统计字典, 第二个单词的字符统计字典)。
无依赖实现方案
如果不想依赖内置的collections.Counter,可以自行实现字符统计逻辑替换对应部分:
def count_chars(s: str) -> dict: count = {} for char in s: count[char] = count.get(char, 0) + 1 return count
内容的提问来源于stack exchange,提问作者José Lima
相关产品推荐
相关产品推荐

