我正在寻找帮助查找Python函数,这些函数允许我获取字符串列表,例如["I like ", " and ", " because "]
和单个目标字符串,例如"I like lettuce and carrots and onions because I do"
,并查找目标字符串中的字符可以按顺序分组的所有方式。你知道吗
例如:
solution(["I like ", " and ", " because ", "do"],
"I like lettuce and carrots and onions because I do")
应返回:
[("I like ", "lettuce", " and ", "carrots and onions", " because ", "I ", "do"),
("I like ", "lettuce and carrots", " and ", "onions", " because ", "I ", "do")]
请注意,在每个元组中,list参数中的字符串都是按顺序排列的,为了实现这一点,函数将返回分割目标字符串的各种可能方法。你知道吗
另一个例子是,这次只有一种可能的组织角色的方法:
solution(["take ", " to the park"], "take Alice to the park")
应给出结果:
[("take ", "Alice", " to the park")]
下面是一个无法正确组织角色的示例:
solution(["I like ", " because ", ""],
"I don't like cheese because I'm lactose-intolerant")
应该回馈:
[]
因为没有办法。注意,第一个参数中的"I like "
不能拆分。目标字符串中没有字符串"I like "
,因此无法匹配。你知道吗
这里是最后一个示例,同样有多个选项:
solution(["I", "want", "or", "done"],
"I want my sandwich or I want my pizza or salad done")
你应该回来
[("I", " ", "want", " my sandwich ", "or", " I want my pizza or salad ", "done"),
("I", " ", "want", " my sandwich or I want my pizza ", "or", " salad ", "done"),
("I", " want my sandwich or I", "want", " my pizza ", "or", " salad ", "done")]`
请再次注意,每个字符串["I", "want", "or", "done"]
都按顺序包含在每个元组中,其余的字符以任何可能的方式围绕这些字符串重新排序。返回的是所有可能的重新排序的列表。你知道吗
注意,还假设列表中的第一个字符串将出现在目标字符串的开头,而列表中的最后一个字符串将出现在目标字符串的结尾。(如果没有,函数应该返回一个空列表。)
什么Python函数允许我这么做?
我尝试过使用regex函数,但在有多个选项的情况下似乎失败了。你知道吗
我有一个解决方案,它需要一个相当多的重构,但它似乎工作, 我希望这有帮助,这是一个相当有趣的问题。你知道吗
输出:
编辑:重构代码以获得有意义的变量名。
添加了我忘记的最后一个案例。
编辑:我已经学会了一些编程技巧,并重新回答了这个问题。你知道吗
回答我的问题,你不需要任何特殊功能。如果你想要一个相对容易编码的版本,请在下面寻找不同的答案。与下面的解决方案相比,此解决方案的文档也较少,但它使用动态编程和记忆体,因此它应该比上一个解决方案更快,并且占用更少的内存。它还正确处理正则表达式字符(例如
|
)。(以下解决方案不适用。)上一个答案:
回答我的问题,
itertools.product
函数和带有overlapped
参数的regex.finditer
是这个解决方案的两个关键函数。我想我应该包括我的最终代码,以防它在类似情况下帮助其他人。你知道吗我真的很关心我的代码是否具有超可读性,所以我最终基于@ktzr的解决方案编写了自己的解决方案。(谢谢!)你知道吗
我的解决方案使用了一些奇怪的东西。你知道吗
首先,它使用一个
overlapped
参数,该参数只能通过regex
模块使用,并且必须安装(很可能是通过pip install regex
)。然后,用import regex as re
将其包含在顶部。这使得在字符串中搜索重叠的匹配项变得很容易。你知道吗第二,我的解决方案使用了一个没有显式包含在库中的itertools函数,您必须这样定义它:
这个函数只允许我成对地遍历一个列表,确保列表中的每个元素(除了第一个和最后一个)都遇到两次。你知道吗
有了这两件事,我的解决方案是:
相关问题 更多 >
编程相关推荐