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



我正在分析单词的语音组成,作为其中的一部分,我一直在使用笛卡尔积将拼写排列与给定单词相匹配。单词中的每个声音都可以用多个拼写表示,程序确定单词中每个声音的正确拼写。列表数量未知,长度未知。

我目前是用户迭代工具的 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 分钟以上的时间来计算。我有数千个单词要分析,所以速度目前是一个问题。

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

我的挑战是,我无法弄清楚如何使用未知数量的未知长度的列表迭代地做到这一点,并且我在任何早期突破递归函数的尝试都失败了。

谁能指出我正确的方向?

for x in in product(*iterables):
if "".join(x) == string:
return x

顺便说一句:你的函数不是递归的 - 这个问题的标题具有误导性。

最新更新