3

这是我的问题:编写一个接受两行输入的程序,我们称第一个针和第二个干草堆。打印针作为 haystack 的子串出现的次数。鼓励我使用循环和等价运算符。

我没有取得太大进展 - 这是我 4 小时后的代码......

..两天后我得到了这个...

needle = 'sses'
haystack = 'assesses'
count = 0                  # initialize the counter
index = haystack.index(needle) # get the first character in the substring
string1 = haystack[index:len(needle) + index] # get the whole substring

for position in range(0,len(haystack)): # loop through the string
    if haystack[position:len(needle) + index] == string1: # match the 1st substring
    count += 1 # iterate the counter
print (count)

...我的问题是,如何让 for 循环计算字符串的第二次出现?

谢谢

蒂姆

最后,“正确”的答案:

needle = input()
haystack = input()
count = 0
if needle in haystack:
    index = haystack.index(needle)
    string1 = haystack[index:len(needle) + index]
    for position in range(0,len(haystack)):
        if haystack[position:len(needle) + position] == string1:
            count += 1
 print (count)
4

1 回答 1

2

让我们逐行分解您的代码:

needle = 'sses'
haystack = 'assesses'
count = 0                  # initialize the counter

到目前为止很好,这只是初始化。

index = haystack.index(needle) # get the first character in the substring

该行已经是一个问题,如果找不到子字符串,则会index引发 a 。ValueError在这种情况下,您的程序会崩溃。您应该改用which 做同样的事情,但如果没有找到子字符串haystack.find(needle),而不是引发ValueError它返回。-1

但是我不明白你为什么使用这条线。您的以下循环将遍历整个循环,haystack并且还将找到needle.

string1 = haystack[index:len(needle) + index] # get the whole substring

needle仅当在上一行中找到此行时才有效。还猜猜string1这条线之后会是什么?您正在提取haystack之前找到 substring的部分needle。所以结果将是string1 == needle,这对你没有任何帮助。

for position in range(0,len(haystack)): # loop through the string

好的,您遍历字符串中的所有位置。

    if haystack[position:len(needle) + index] == string1: # match the 1st substring

所以在这里我不明白为什么你想再次找到你之前已经找到的第一次出现。你不想检查是否有匹配position项,无论是第一个还是第二个或第三个......一个?所以我猜这haystack[position:len(needle) + index]应该提取haystack从位置开始position并且长度为needle. 但是为什么会有+ index呢?第一次出现(保存在 中index)与此有什么关系?你不是说+ position这里吗?最后,您正在比较string1我所说的(如果您的代码进入这一行)等于needle. 那么为什么不直接比较needle呢?

    count += 1 # iterate the counter

此行在您发布的代码中缩进错误,它应该比 if 语句更深。

最后,您必须在 for 循环中考虑,如果position到达末尾,haystack可能不再有长度len(needle)开始的子字符串position。因此,您可能希望在此之前停止迭代。(编辑:我只是注意到代码无论如何都会正确运行。没有必要在 python 中解决这个问题,因为允许使用超出字符串范围的索引,但它会在其他语言中。)

我想这是一个练习,但如果不是这样,在 python: 中会有更简单的方法来做到这一点count = haystack.count(needle)。不过,您提出的算法有一点不同。string.count(substring)将返回非重叠匹配的数量,而您当前的代码将找到非重叠和重叠匹配的数量。您发布的练习不清楚两者中的哪一个。但是如果你应该只找到不重叠的结果,你也需要在你的 for 循环中考虑这一点。

还可以对代码的样式和性能进行一些改进,但我不会深入讨论,因为您似乎根本无法让它工作。

于 2014-01-02T03:06:50.543 回答