Can't get my count function to work in Python

11,902

Solution 1

Changing your count function to the following passes the tests:

def count(phrase, word):
    count1 = 0
    num_phrase = len(phrase)   
    num_letters = len(word)    
    for i in range(num_letters):
        if word[i:i+num_phrase] == phrase:
          count1 += 1
    return count1

Solution 2

Use str.count(substring). This will return how many times the substring occurs in the full string (str).

Here is an interactive session showing how it works:

>>> 'Mississippi'.count('is')
2
>>> 'banana'.count('an')
2
>>> 'banana'.count('ana')
1
>>> 'banana'.count('nana')
1
>>> 'banana'.count('nanan')
0
>>> 'aaaaaa'.count('aaa')
2
>>> 

As you can see, the function is non-overlapping. If you need overlapping behaviour, look here: string count with overlapping occurrences

Share:
11,902
user1091975
Author by

user1091975

Updated on June 14, 2022

Comments

  • user1091975
    user1091975 almost 2 years

    I'm trying to create a function where you can put in a phrase such as "ana" in the word "banana", and count how many times it finds the phrase in the word. I can't find the error I'm making for some of my test units not to work.

    def test(actual, expected):
        """ Compare the actual to the expected value,
            and print a suitable message.
        """
        import sys
        linenum = sys._getframe(1).f_lineno   # get the caller's line number.
        if (expected == actual):
            msg = "Test on line {0} passed.".format(linenum)
        else:
            msg = ("Test on line {0} failed. Expected '{1}', but got '{2}'.".format(linenum, expected, actual))
        print(msg)
    
    def count(phrase, word):
        count1 = 0
        num_phrase = len(phrase)   
        num_letters = len(word)    
    
        for i in range(num_letters):
            for x in word[i:i+num_phrase]:
                 if phrase in word:
                     count1 += 1
                 else:
                     continue    
            return count1
    
    def test_suite():
        test(count('is', 'Mississippi'), 2)
        test(count('an', 'banana'), 2)
        test(count('ana', 'banana'), 2)
        test(count('nana', 'banana'), 1)
        test(count('nanan', 'banana'), 0)
        test(count('aaa', 'aaaaaa'), 4)
    
    test_suite()
    
  • user1091975
    user1091975 over 12 years
    Thanks. I don't know how I overlooked that. I guess I just make my function too complicated.
  • MattH
    MattH over 12 years
    If you're searching for and/or in large strings there are several algorithms to speed up the search.