从字谜中寻找回文

时间:2012-12-03 01:57:41

标签: python

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

输入的原始回文将来自'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()

1 个答案:

答案 0 :(得分: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''path/to/palsfile',那么您可以按如下方式调用main

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

希望这有帮助