【问题标题】:Minimum number of manipulations for anagrams字谜的最小操作次数
【发布时间】:2019-03-05 20:36:00
【问题描述】:

给定一个字符串,我们必须将其拆分为两个连续的子字符串,然后确定要更改的最小字符数以使两个子字符串成为彼此的字谜。

def anagram(s):
    flag = 0
    if len(s)%2 != 0: return -1
    else:
        temp1,temp2 = s[:len(s)//2],s[len(s)//2:]  
        temp1 = ''.join(sorted(temp1))
        temp2 = ''.join(sorted(temp2))

        for i in temp1:
            flag1 = temp2.count(i)
            if flag1>1: flag1 = 1
            else: flag1 = flag1
            flag += flag1
    return flag 

我有点不知所措,并且在没有做对的情况下使这件事变得非常复杂。有什么办法可以简化逻辑?

【问题讨论】:

  • 很遗憾,您忘记提问了。
  • @timgeb:这是含蓄的,但我现在更正了。
  • 抱歉,不够具体。您的测试用例是什么,程序是如何失败的,您是否已经知道失败的原因?

标签: python anagram


【解决方案1】:

为了找到一个单词的所有字谜,我使用了 SOWPODS 词典。这是下载链接:https://osdn.net/projects/sfnet_scrabbledict/downloads/Dictionary%20Files/sowpods.txt.gz/

def anagrams(s):
    text_file = open("sowpods.txt", "r")
    lines = text_file.readlines()
    words = [y.replace('\n','') for y in lines]
    result = [words[i] for i in range(0,len(words)-1) if ((''.join(set(sorted(s)))) == (''.join(set(sorted(words[i])))))]
    return result

在文件打开命令中,最好给出你的 SOWPODS 字典的链接。

【讨论】:

    猜你喜欢
    • 2020-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-12
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    相关资源
    最近更新 更多