2

i was wondering if anyone could help me figure out how to write a piece of code that would analyze the input a user would put in and count the amount of times a specific word is occurring.

For example, user is prompted to input a string. types in bobobob. We are searching for how many times "bob" appears in this code, and so the answer would be 3.

If this could be done in a for loop/if-else statement without any imports, i would like to see how.

This is what i have, and for some reason its coming up short on most tests

s = raw_input("string: ")
count = len(s.split("bob"))
print count

for example, if you test hoboboobbobbbobobbopbbobbbpbooboboboobbobovob you get 7 instead of 8.

I need to be able to do this without regex or any other imports.

Robert Bedrosian
  • 47
  • 1
  • 2
  • 7
  • Using `s.split("bob")` will not work because overlapping sequences (as in "bobob" will be split like `["bob", "ob"]` – VHarisop Jan 19 '15 at 08:47
  • This does appear to be homework/coursework - I really don't understand what is happening to education if students are resorting to external help so early in their courses. this is hardly difficult. – Tony Suffolk 66 Jan 19 '15 at 08:57

2 Answers2

1

If you are just looking for a quick answer this will work!

t = "hoboboobbobbbobobbopbbobbbpbooboboboobbobovob"
l = "bob"
count = 0
for x in range(len(t)-len(l)+1):
    if (l == t[x:x+len(l)]):
        count += 1

print(count)

You can turn that into a function and pop it in there instead of s.split()

  • Could you explain how you came up with the for loop and why it works? – Robert Bedrosian Jan 19 '15 at 09:03
  • of course! We have to iterate through t and grab every possible 3 letter substring to see if it equals bob. We first find the parameters of the loop we know "bob" should be iterated through once, while "bobob" should iterated through 3 times. Looking at that, we see that the number of iterations should be the (length of t) - (length of l) +1. next we get the substring, t[x:x+len(l)] is using slicing to grab a substring, heres a quick explanation of slicing [link](http://stackoverflow.com/questions/509211/explain-pythons-slice-notation) – Jackson Darrow Jan 19 '15 at 21:35
  • thank you very much appreciate it! however, shouldnt bobob be iterated twice? Im not understanding why we are adding 1 – Robert Bedrosian Jan 21 '15 at 01:34
0
def substring_counter(string, sub_string):
    count = 0
    for i in range(len(string)-len(sub_string)):
        if string[i:i+len(sub_string)] == sub_string:
            count += 1
    return count

Using list comprehension:

def substring_counter_lc(s, c):
    return len([i for i in range(len(s)-len(c)) if s[i:i+len(c)] == c])

In action:

>>> substring_counter('hoboboobbobbbobobbopbbobbbpbooboboboobbobovob', 'bob')
8
>>> substring_counter_lc('hoboboobbobbbobobbopbbobbbpbooboboboobbobovob', 'bob')
8
Inbar Rose
  • 41,843
  • 24
  • 85
  • 131