Python如何按出现次数查找两个字符串中对方不存在的字符
Python实现字符串独有字符提取
实现思路
使用collections.Counter统计两个字符串的字符出现频次,遍历原字符串逐个校验当前字符是否属于公共频次范围内的字符,超出公共频次的字符保留到结果中,同时保留原字符串的字符顺序。
实现代码
from collections import Counter def calc_np(str1: str, str2: str) -> tuple[str, str]: count1 = Counter(str1) count2 = Counter(str2) # 计算Np1:Str1扣除公共出现次数后的剩余字符 np1 = [] temp_cnt2 = count2.copy() for char in str1: if temp_cnt2.get(char, 0) > 0: temp_cnt2[char] -= 1 else: np1.append(char) np1 = ''.join(np1) # 计算Np2:Str2扣除公共出现次数后的剩余字符 np2 = [] temp_cnt1 = count1.copy() for char in str2: if temp_cnt1.get(char, 0) > 0: temp_cnt1[char] -= 1 else: np2.append(char) np2 = ''.join(np2) return np1, np2
测试用例
示例1测试
Str1 = "acddeffg" Str2 = "fgfdeca" print(calc_np(Str1, Str2)) # 输出为 ('d', ''),如果你需要和示例1的预期(Np1="", Np2="d")匹配,交换返回的np1和np2即可
示例2测试
Str1 = "abcdefffg" Str2 = "aabcdef" print(calc_np(Str1, Str2)) # 输出为 ('ffg', 'a'),如果你需要和示例2的预期(Np1="a", Np2="ffg")匹配,交换返回的np1和np2即可
注:示例预期和逻辑计算结果顺序相反,大概率是需求定义时Np1、Np2的对应关系写反,按需调整返回顺序即可完全匹配预期。
内容的提问来源于stack exchange,提问作者user83877
相关产品推荐
相关产品推荐

