Python - 如何提升填字游戏解题器的速度

1 投票
2 回答
1904 浏览
提问于 2025-04-17 17:14

我有一个函数,它是一个填字游戏解答器的一部分:

def CrosswordPossibleWords(p_words, p_cw_words):
    """For each word found in the crossword, find the possible words and keep track of the one with the minimum possible words.

    Keyword arguments:
    p_words    -- The dictionary words.
    p_cw_words -- The crossword word attributes.
    """
    l_min = 999999999
    l_min_index = -1
    l_index = 0
    l_choices = []
    for l_cw_word in p_cw_words:
        if l_cw_word[2] >= l_min_length and '-' in l_cw_word[4]:
            pattern = re.compile('^' + l_cw_word[4].replace('.', '%').replace('-', '.').upper() + '$', re.UNICODE)
            l_choice = []
            for l_word in [w for w in p_words if len(w) == len(l_cw_word[4])]:
                if re.match(pattern, l_word):
                    l_choice.append(l_word)
            l_choices.append(l_choice)
            if len(l_choice) < l_min:
                l_min_index = l_index
                l_min = len(l_choice)
        else:
            l_choices.append([])
        l_index = l_index + 1
    return (l_choices, l_min_index)

填字游戏中的单词格式是:

[row, col, length, direction, word]

如果我无法解出某个单词,我会在这个单词中放一个'.',如果我不知道某个字母,我会放一个'-'

我该如何让这段代码运行得更快呢?现在运行大约需要2.5秒。我在考虑使用numpy字符串,因为听说numpy快十倍,但我对numpy一无所知,也不知道能否用它来做我现在用的所有字符串操作。

有什么建议吗?

2 个回答

1

虽然我同意Scott Hunter的观点,但你可能在寻找这样的东西,其中列表被字典替代:

def CrosswordPossibleWords(p_words, p_cw_words):
    """For each word found in the crossword, find the possible words and keep track of the one with the minimum possible words.

    Keyword arguments:
    p_words    -- The dictionary words.
    p_cw_words -- The crossword word attributes.
    """
    l_min = 999999999
    l_min_index = -1
    l_index = 0
    l_choices = {}    # using dict instead of list
    for l_cw_word in p_cw_words:
        if l_cw_word[2] >= l_min_length and '-' in l_cw_word[4]:
            pattern = re.compile('^' + l_cw_word[4].replace('.', '%').replace('-', '.').upper() + '$', re.UNICODE)
                l_choice = {}  # using dict instead of list

            for l_word in [w for w in p_words if len(w) == len(l_cw_word[4])]:
                if re.match(pattern, l_word):

                    l_choice[l_word]=None

            l_choices[l_choice]=None

            if len(l_choice) < l_min:  ##
                l_min_index = l_index  ## Get rid of this.
                l_min = len(l_choice)  ##
        else:
            l_choices.append([])    # why append empty list?
        l_index = l_index + 1
        l_choices=list(l_choices.keys())   # ...you probably need the list again...
    return (l_choices, l_min_index)
1

你可以在调用这个函数之前,先按照单词的长度把你的字典分好类,这样每次调用的时候就不用重新分类了。

撰写回答