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

Python对称词对查找代码重复输出问题的修正求助

问题:查找互为反转的词对时出现重复输出

要实现从列表中找出互为反转的词对功能,但当前代码会输出重复的词对(比如同时出现am & ma和ma & am),修改切片参数、将集合add改为update都未解决问题。

原代码

def find_pairs(words):
    word_set = set(words)
    # Initialize a set to store the symmetric pairs of words
    result = set()
    # Iterate through each word in the set
    for word in word_set:
        # Create the reverse of the word
        reverse = word[::-1]
        if reverse in word_set and word != reverse:
            # Add the word and its reverse to the result set
            result.add(f"{word} & {reverse}")
    for pair in result:
        print(pair)

# Test the function with different test cases and print the result
find_pairs(["am","at","ma","if","fi"])      # ma & am, fi & if
print("=============")
find_pairs(["ab", "bc", "cd", "de", "ba"])  # ba & ab
print("=============")
find_pairs(["ab","ba","ac","ad","da","ca"]) # ba & ab, da & ad, ca & ac
print("=============")
find_pairs(["ab", "ac"])                    # None
print("=============")
find_pairs(["ab", "aa", "ba"])              # ba & ab
print("=============")
find_pairs(["23","84","49","13","32","46","91","99","94","31","57","14"])
                                            # 32 & 23, 94 & 49, 31 & 13

问题原因

遍历集合时,每个词对会被处理两次:比如遍历am时会添加am & ma,遍历ma时又会添加ma & am,这两个是同一对的不同表述,导致结果重复。

修复方案

核心思路是确保每一对只被记录一次,以下两种方法均可实现:

方法1:按字符串大小过滤,仅添加一次

在判断条件中增加word < reverse,仅当原词的字符串顺序小于反转词时才添加,避免重复记录。

修改后的代码:

def find_pairs(words):
    word_set = set(words)
    result = set()
    for word in word_set:
        reverse_word = word[::-1]
        if reverse_word in word_set and word != reverse_word and word < reverse_word:
            result.add(f"{word} & {reverse_word}")
    for pair in result:
        print(pair)

# 测试用例输出符合预期
find_pairs(["am","at","ma","if","fi"])      # am & ma, if & fi
print("=============")
find_pairs(["ab", "bc", "cd", "de", "ba"])  # ab & ba
print("=============")
find_pairs(["ab","ba","ac","ad","da","ca"]) # ab & ba, ac & ca, ad & da
print("=============")
find_pairs(["ab", "ac"])                    # 无输出
print("=============")
find_pairs(["ab", "aa", "ba"])              # ab & ba
print("=============")
find_pairs(["23","84","49","13","32","46","91","99","94","31","57","14"])
                                            # 13 & 31, 23 & 32, 49 & 94

方法2:用排序后的元组统一词对格式

将词与反转词组成元组并排序,同一对的元组会因排序保持一致,再转成字符串加入集合,自动实现去重。

修改后的代码:

def find_pairs(words):
    word_set = set(words)
    result = set()
    for word in word_set:
        reverse_word = word[::-1]
        if reverse_word in word_set and word != reverse_word:
            # 排序后生成统一格式的字符串
            sorted_pair = tuple(sorted((word, reverse_word)))
            result.add(f"{sorted_pair[0]} & {sorted_pair[1]}")
    for pair in result:
        print(pair)

# 测试用例输出与方法1一致

两种方法都能解决重复输出问题,输出的词对格式统一,符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 04:35:46