You need to enable JavaScript to run this app. Python实现带重复计数的序列交集及花括号格式输出方法咨询
优惠活动
大模型
产品
解决方案
定价
更多

Python实现带重复计数的序列交集及花括号格式输出方法咨询

重复计数逻辑修正

原代码的核心缺陷是遍历第一序列元素时,仅判断元素是否存在于第二序列,未跟踪已匹配的元素数量,导致最终结果的重复次数完全以第一序列为准,未取两个序列的较小出现值。
两种可落地的修正方案:

方案1:基于Counter统计(推荐)

利用Python标准库collections.Counter的频次统计能力,其自带的交集运算符&会自动对公共元素取两个序列中的最小出现次数,逻辑简洁且执行效率高。

from collections import Counter

# 读取并分割输入序列
seq1 = input("Please enter the space-separated elements of the first set: ").split()
seq2 = input("Please enter the space-separated elements of the second set: ").split()

# 统计两个序列的元素频次
count1 = Counter(seq1)
count2 = Counter(seq2)
# 交集运算自动取公共元素的最小出现次数
intersection_freq = count1 & count2

# 将频次结果展开为元素列表
listOfIntersection = []
for elem, freq in intersection_freq.items():
    listOfIntersection.extend([elem] * freq)

对应测试输入的计算逻辑:第一序列中12出现3次、hi出现1次、1.5出现1次;第二序列中12出现2次、hi出现3次、1.5出现1次。最终交集的频次为12:2、hi:1、1.5:1,展开后完全匹配预期的元素重复次数。

方案2:临时列表移除匹配项(无依赖)

无需导入第三方模块,直接将第二序列拷贝为可变临时列表,每匹配到一个元素就从临时列表中移除对应项,自然实现重复次数取小的效果。

# 读取并分割输入序列
seq1 = input("Please enter the space-separated elements of the first set: ").split()
seq2 = input("Please enter the space-separated elements of the second set: ").split()

# 生成第二序列的临时副本,避免修改原始输入
temp_seq2 = seq2.copy()
listOfIntersection = []

for elem in seq1:
    if elem in temp_seq2:
        listOfIntersection.append(elem)
        # 匹配一次即从临时列表移除对应元素,避免重复匹配
        temp_seq2.remove(elem)

该方案适合轻量场景,当序列长度较大时,列表的remove操作时间复杂度较高,效率低于Counter方案。

输出格式调整

原代码直接打印列表对象,会输出Python列表的原生格式(带方括号、字符串元素附带引号)。要实现花括号包裹、元素无引号的指定格式,只需将结果列表的元素用, 拼接后,外层包裹花括号即可:

output = "{" + ", ".join(listOfIntersection) + "}"
print(output)

对应测试输入,该代码输出内容为{12, 12, 1.5, hi},完全匹配预期格式。

完整可运行代码(基于Counter方案)
from collections import Counter

print("This program finds the intersection of two sets")
seq1 = input("Please enter the space-separated elements of the first set: ").split()
seq2 = input("Please enter the space-separated elements of the second set: ").split()

count1 = Counter(seq1)
count2 = Counter(seq2)
intersection_freq = count1 & count2

listOfIntersection = []
for elem, freq in intersection_freq.items():
    listOfIntersection.extend([elem] * freq)

output = "{" + ", ".join(listOfIntersection) + "}"
print(output)

测试运行效果:
输入第一序列:12 k e 34 1.5 12 hi 12 0.2
输入第二序列:1.5 hi 12 0.1 54 12 hi hi hi
程序输出:{12, 12, 1.5, hi}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.29 23:15:04