3

我试图从生成的字谜列表中找到回文。这里的转折是我的初始输入是一个回文列表。我本质上是在尝试自动寻找回文,它是回文的字谜(不是家庭作业,只是一个英语书呆子)。

输入的原始回文将来自“pals.txt”,其中回文是行分隔的,并且已删除空格和非数字字符。我正在使用英英词典文件“dictionary.txt”来生成字谜。

我将不胜感激任何输入,因为我仍然是一个初级程序员。谢谢!

def isPalindrome(s):
    return s.lower() == s[::-1].lower()

def anagramchk(word,chkword):
    for letter in word:
        if letter in chkword:
            chkword = chkword.replace(letter, '', 1)
        else:
            return 0
    return 1

f0 = open('pals.txt', 'r')
f1 = open('dictionary.txt', 'r')
for line in f0:
    wordin = line
    for line in f1:
        line = line.strip()
        if len(line) >= 4:
            if anagramchk(line, wordin):
                if isPalindrome(line):
                    print line
f0.close()
f1.close()
4

1 回答 1

2
import collections

def isPalindrome(s):
    return s.lower() == s[::-1].lower()

def anagramchk(word,chkword):
    return sorted(word.lower()) == sorted(chkword.lower())

def allAnagrams(dictfilepath):
    answer = collections.defaultdict(list)
    with open(dictfilepath) as dictfile:
        for line in dictfile:
            word = line.strip().lower()
            answer[''.join(sorted(word))].append(word)
    return answer

def fetchAllAnagrams(wordin, anagrams):
    return anagrams[''.join(sorted(wordin.lower()))]

def main(dictfilepath, palsfilepath):
    anagrams = allAnagrams(dictfilepath)
    with open(palsfilepath) as palfile:
        for line in palfile:
            word = line.strip().lower()
            if isPalindrome(word):
                for anagram in anagrams[''.join(sorted(word))]:
                    if isPalindrome(anagram):
                        print "%s is an anagram of %s" %(anagram, word)

假设你的文件路径是'path/to/dictfile'and 'path/to/palsfile',那么你可以调用main如下:

main('path/to/dictfile', 'path/to/palsfile')

希望这可以帮助

于 2012-12-03T02:05:56.657 回答