我编写了一个函数,它返回带有重复的字符串的所有可能“产品”的列表(用于拼写检查程序):
def productRepeats(string):
comboList = []
for item in [p for p in product(string, repeat = len(list(string)))]:
if item not in comboList:
comboList.append("".join(item))
return list(set(comboList))
因此,当输入 print(productRepeats("PIP"))
时,他的输出是(我不在乎顺序是什么):
['PII', 'IIP', 'PPI', 'IPI', 'IPP', 'PPP', 'PIP', 'III']
但是,如果我尝试任何大于 5 位数字 (PIIIIP) 的内容,即使只有 64 种方式,也需要大约 30 秒才能输出
有什么方法可以加快速度,例如获取字符串“GERAWUHGP”的列表需要半个多小时?
最佳答案
在调用product()
之前消除重复项
product(seq, Repeat=len(seq))
当且仅当 seq
包含任何重复元素时才会产生重复结果;例如,product('ABC', Repeat=3)
不会有重复项,但 product('ABA', Repeat=3)
会有一些重复项,因为 A
将被多次选择(并且“ABA”被用作参数 3 次,这一事实将使情况更加复杂)。首先从 string
中过滤掉任何重复项,然后将结果传递给 product
,这样您就可以完全删除 product
后的重复项检查,所以你可以直接返回product
的结果:
def productRepeats(string):
return product(set(string), repeat=len(string))
关于python - 加速 Python 中输出重复产品的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51002355/