Python Forum
Substring Counting - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Substring Counting (/thread-7666.html)



Substring Counting - shelbyahn - Jan-20-2018

I am working through the Computer Science Circles Web lesson for learning Python and I am stuck on one exercise. Here are the directions:

As mentioned in lesson 7A, a substring is any consecutive sequence of characters inside another string. The same substring may occur several times inside the same string: for example "assesses" has the substring "sses" 2 times, and "trans-Panamanian banana" has the substring "an" 6 times. Write a program that takes two lines of input, we call the first needle and the second haystack. Print the number of times that needle occurs as a substring of haystack.

Here is what I have so far:

needle = input()
haystack = input()
for s in range (0, len(haystack)):
x = 0
haysub = haystack[s : len(needle) + s]
if haysub == needle:
x = x + 1
if haysub != needle:
continue
print(x)


RE: Substring Counting - Mekire - Jan-20-2018

Welcome to the forum, please use code tags in the future around your code (the python button you see when posting).

Seems your answer is almost correct except you are setting x to 0 every time through the loop.
With that outside the loop it seems to work:
x = 0
for s,_ in enumerate(haystack):
    haysub = haystack[s:len(needle) + s]
    if haysub == needle:
        x += 1

print(x)



RE: Substring Counting - shelbyahn - Jan-21-2018

Thanks Mekire.

I am very new and I don't quite understand what you mean by the tags. Could you explain that in a bit more depth?


RE: Substring Counting - j.crater - Jan-21-2018

It is a way to edit post so Python code, or outputs, or errors... are more readable. Mekire used Python code tags with the code he posted in his reply to you. You can read more about it here:
https://python-forum.io/misc.php?action=help&hid=25


RE: Substring Counting - krisputas - Jan-13-2022

(Jan-20-2018, 04:36 AM)Mekire Wrote:
x = 0
for s,_ in enumerate(haystack):
    haysub = haystack[s:len(needle) + s]
    if haysub == needle:
        x += 1

print(x)

I seem to be not understanding something with how the loops work. Could you please elaborate in a simple manner why in line 4 you've used the +s part?

Thank you