我需要反转几个字母并停止打印几行代码

I need to reverse several letters and stop printing several lines of code

提问人:BigEdit 提问时间:2/9/2023 更新时间:2/9/2023 访问量:60

问:

我需要保留几封信。我保留的代码重复了额外的行和列。我不确定我需要调整什么才能使代码正常工作。 代码是用 python 编写的。

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

我试图更改其中的数字以减少重复的代码行 - 没有改进。 反向 = word[::-1]

第二个目标是将“添加”更改为“更新”。更新减少了行数,但没有打印出完整的代码。

result.add(f“{word} & {reverse}”) 原始代码重复了更多,所以我丢弃了那个。

# for words in words:
    #     reverse = ""
    #     reverse = words[1] + words[0]
    #     print(words, reverse)
python-3.x 字符串 切片 反转

评论


答:

0赞 Samathingamajig 2/9/2023 #1

无需将格式化的字符串存储在集合中,只需存储两个值中的一个(用于确保它始终是添加的值),然后在之后对其进行格式化resultmax

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 maximum of word and reverse to the result set
            result.add(max(word, reverse))
    for word in result:
        # print out the formatted version
        print(f"{word} & {word[::-1]}")

评论

0赞 BigEdit 2/9/2023
谢谢!我按照您的建议更改了代码,我将研究最大值并弄清楚如何使用它。
0赞 Shorn 2/9/2023 #2

我对 @Samathingamajig有一个非常相似的答案,但是如果结果中已经有相反的情况,我只是在 if 语句中添加一个检查,而不是使用 max。唯一的区别是他们的版本会尝试将其添加到集合中,如果它存在,这将失败,而我的版本会检查是否存在相反的情况,并且根本不尝试添加它。

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 and reverse not in result:
            # Add the word and its reverse to the result set
            result.add(word)
    for word in result:
        reverse = word[::-1]
        print(f"{word} & {reverse}")
0赞 hlidka 2/9/2023 #3

如果要减少代码行数,则可以缩短代码行数:

from collections import Counter

def find_pairs(words):
  return [k for k, v in Counter(map(lambda w: "{} & {}".format(
      *sorted([w, w[::-1]])), words)).items() if v > 1]

评论

0赞 BigEdit 2/9/2023
谢谢Hlidka!与我的代码相比,这更短。我将研究如何使用计数器和 lambda。