Jan-20-2018, 02:16 AM
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)
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)