【发布时间】:2016-09-26 18:24:05
【问题描述】:
问题:
我需要满足以下条件的所有字符序列:
- 字符序列必须出现多次((LE, 1) 因此无效)。
- 字符序列必须长于一个字符((M, 2) 因此无效)。
- 字符序列不能是存在相同次数的较长现有序列的一部分(因此,如果存在 (LIO, 2),则 (LI, 2) 无效)。
所以,如果输入字符串是:KAKAMNENENELIOLELIONEM$
输出将是:
(KA, 2)
(NE, 4)
(LIO, 2)
它还需要速度快,它应该能够在合理的时间内解决一个 1000 字符长的字符串。
我尝试过的:
从后缀树中获取分支数量:
编辑this suffix tree -creating librabry(Python-Suffix-Tree),我做了一个程序,结果有些错误。
我在 suffix_tree.py 的 SuffixTree 类中添加了这个函数:
def get_repeated_substrings(self):
curr_index = self.N
values = self.edges.values()
values = sorted(values, key=lambda x: x.dest_node_index)
data = [] # index = edge.dest_node_index - 1
for edge in values:
if edge.source_node_index == -1:
continue
top = min(curr_index, edge.last_char_index)
data.append([edge.source_node_index,
self.string[edge.first_char_index:top+1]])
repeated_substrings = {}
source_node_indexes = [i[0] for i in data]
nodes_pointed_to = set(source_node_indexes)
nodes_pointed_to.remove(0)
for node_pointed_to in nodes_pointed_to:
presence = source_node_indexes.count(node_pointed_to)
key = data[node_pointed_to-1][1]
if key not in repeated_substrings:
repeated_substrings[key] = 0
repeated_substrings[key] += presence
for key in repeated_substrings:
if len(key) > 1:
print(key, repeated_substrings[key])
然后像这样使用它和库的其余部分:
from lib.suffix_tree import SuffixTree
st = SuffixTree("KAKANENENELIOLELIONE$")
print(st.get_repeated_substrings())
输出:
KA 2
NE 7
LIO 2
IO 4
get_repeated_substrings() 基本上遍历节点之间的所有连接(在这个库中称为边)并保存它指向的节点有多少连接(它将它保存到repeated_substrings),然后它打印保存的值更多长度超过一个字符。
它将连接数附加到该序列已有的数量上,这在大多数情况下都有效,但正如您在上面的输出中看到的那样,它导致 'NE' 的值不正确(7,它应该是4)。解决了这个问题后,我意识到这种方法无法检测出由相同字符(AA、BB)组成的图案以及其他故障。我的结论:要么没有办法用后缀树解决它,要么我做错了什么。
其他方法:
我也尝试了一些更直接的方法,包括循环遍历内容,但这也没有成功:
import copy
string = 'kakabaliosie'
for main_char in set(string):
indices = []
for char_i, char in enumerate(string):
if main_char == char:
indices.append(char_i)
relative = 1
while True
for index in indices:
other_indices = copy.deepcopy(indices)
other_indices.remove(index)
for other_index in other_indices:
(无法完成)
问题:
我怎样才能制作出我想要的程序?
【问题讨论】:
-
@BenHare 对我的问题 shure 写一个建设性的答复确实需要一些“工作”,但我认为我的问题不符合“让别人为你做你的工作”的资格。毕竟,我这几天一直在尝试以多种不同的方式解决这个问题(我在问题中提供了最突出的方式)。
-
以你为例。如果我们有 (LIO, 2),那么 (IO, 2) 是否也必须被忽略?此外,输出不正确:子字符串
ELIO可以找到两次,但未在结果中列出。ENE相同,有两个重叠匹配。 -
@Rerito 谢谢,你是对的。是的,如果我们有 (LIO, 2),则 (IO, 2) 应该被忽略。
标签: python string algorithm suffix-tree