0

我想要一个程序在文件中查找字谜。例如:

>>>anagram('words.txt', 'top')
top
pot

该文件将包含一长串没有空格的单词。

tapmatlamebrainfamelookcookkoolkoocnamemane

这是我当前的代码:

def anagrams(filename, word):
    infile = open(filename, 'r')
    if not word:
        return ['']
    ret = []
    for i, d in enumerate(word):
        perms = anagrams(word[:i] + word[i+1:])
        for perm in perms:
            ret.append(d + perm)
    for i in ret:
        if i in infile:
            print (i)
        else:
            pass
4

1 回答 1

1

这应该做我认为你想要它做的事情

def anagram(filepath, word):
    with open(filepath) as f:
        text = ''.join(line.strip() for line in file)
    for i in xrange(len(text)-len(word):
        prop = text[i:i+len(word)]
        if all(char in word for char in prop) and all(prop.count(char) == prop.count(word) for char in prop):
            print prop

请注意,如果您的文件只有两个单词“hi”和“there”作为“hithere”,并且您查找“ith”的字谜,"hit"将被打印

于 2012-10-22T01:35:20.940 回答