【发布时间】:2011-10-22 16:41:28
【问题描述】:
我正在自学基本编程。
一个简单的项目是查找字符串中子字符串的重复索引。例如,在字符串“abcdefdef”和子字符串“def”中,我希望输出为 3 和 6。我编写了一些代码,但没有得到我想要的答案。以下是我写的
注意:我知道可能有更简单的方法来产生结果,利用语言的内置功能/包,例如正则表达式。我也知道我的方法可能不是最佳算法。不过,此时,我只是在寻求有关修复以下逻辑的建议,而不是使用更惯用的方法。
import string
def MIT(String, substring): # "String" is the main string I'm searching within
String_list = list(String)
substring_list = list(substring)
i = 0
j = 0
counter = 0
results = []
while i < (len(String)-1):
if [j] == [i]:
j = j + 1
i = i + 1
counter = counter + 1
if counter == len(substring):
results.append([i - len(substring)+1])
counter = 0
j = 0
i = i+1
else:
counter = 0
j = 0
i = i+1
print results
return
我的推理是这样的。我将字符串和子字符串变成一个列表。这允许对字符串中的每个字母进行索引。我设置 i 和 j = 0——这将分别是我在字符串和子字符串索引中的第一个值。我还有一个新变量 counter,我将其设置为 0。基本上,我使用 counter 来计算位置 [i] 中的字母等于位置 [j] 中的元素的次数。如果 counter 等于子字符串的长度,那么我知道 [i - len(substring) + 1] 是我的子字符串开始的位置,所以我将它添加到名为 results 的列表中。然后我重置 counter 和 j 并继续搜索更多子字符串。
我知道代码很笨拙,但我认为我仍然应该能够得到答案。相反,我得到:
>>> MIT("abcdefghi", "def")
[[3]]
>>> MIT("abcdefghi", "efg")
[[3]]
>>> MIT("abcdefghi", "b")
[[1]]
>>> MIT("abcdefghi", "k")
[[1]]
有什么想法吗?
【问题讨论】:
-
这对codereview.stackexchange.com来说似乎是个好问题
-
@Gerrat codereview 仅适用于 working 代码 - 但自 2011 年以来规则可能已更改。