一旦找到解决方案,如何尽早脱离笛卡尔积递归函数?

问题描述 投票:1回答:1

我正在分析单词的语音组成,为此,我一直在使用笛卡尔乘积来匹配给定单词的拼写排列。单词中的每个声音都可以用几种拼写形式表示,程序会为单词中的每种声音确定正确的拼写形式。列表数量未知,长度未知。

我目前是列表理解内的用户itertools的product(),即强行使用,在返回值之前检查了每个排列。这是Python 3中的相关部分:

from itertools import product


def cartesian_match(string, iterables):
    """Gets the phonetic spelling breakdown of a word via cartesian product.

    Args:
        string (str):     String for which a matched spelling is wanted.
        iterables (list): A list of lists of unknown number and length.
                          Each sublist contains only str elements.
                          Each sublist contains all possible spellings of a
                          phoneme.

    Returns:
        list: the first matched list of spelling units.

    Example (simplified):
      Args:
        string = "python"
        iterables = [
          'p', 'pp'],['i', 'ie', 'y', 'igh'],['th'],['or', 'ou', 'e', 'o'],[
          'nd', 'nn', 'n', 'ne']

      Returns:
        ['p', 'y', 'th', 'o', 'n']

    """
    return [x for x in product(*iterables) if "".join(x) == string][0]

对于复杂的单词,笛卡尔积很大,有数千万个排列。有些单词最多需要15分钟才能计算出来。我要分析成千上万个单词,因此当前速度是个问题。

为了加快处理速度,我需要一个函数,该函数在发现值后立即返回该值,而不是形成笛卡尔乘积并必须遍历每个排列。它还使我可以优化每个子列表中元素的顺序,以便更快地获得匹配的值。

我的挑战是,我无法弄清楚如何使用未知数量的未知长度的列表来迭代地执行此操作,而且在尽早打破递归函数的任何尝试中都失败了。

有人能指出我正确的方向吗?

python python-3.x recursion itertools cartesian-product
1个回答
1
投票
BTW:您的函数不是递归的-此问题的标题具有误导性。
© www.soinside.com 2019 - 2024. All rights reserved.