0

Algorithm: - Go through each character in word1, one by one. If this character occurs in word2, then add 1 to the count. Return total count after you're done going through the characters.

>>>count_common_occurrences('bob y', 'bobbette z')
    3
>>>count_common_occurrences('bobbette z', 'bob y')
    4

Here is my code

def count_common_occurrences(word1, word2):
    count = 0 
    for i in word1.strip():
        if i in word2.strip():
            count = count + 1
    return count

the result I get is always one greater than that of the example, I was intially suspecting the function counted space, so I used strip but after that the result is still the same. I dont know whats causing the function to count one more than its supposed to

sudo97
  • 904
  • 2
  • 11
  • 22
Beier Mu
  • 51
  • 4

1 Answers1

1

It's counting the space character as a match and so it returns one more than you expect.

The very simplest fix, is to check for the space char and skip it.

def count_common_occurrences(word1, word2):
    count = 0 
    for i in word1.strip():
        if i != ' ':
            if i in word2.strip():
                count = count + 1
    return count

print(count_common_occurrences('bob y', 'bobbette z'))
print(count_common_occurrences('bobbette z', 'bob y'))
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
  • 1
    thank you so much, I thought that by using the built-in function strip it would eliminate the space, and just comparing the two function without spaces, but turns out that not how it works – Beier Mu Feb 14 '20 at 03:56
  • strip is only taking away preceding and trailing white space. To take out all whitespace you can look [here](https://stackoverflow.com/questions/8270092/remove-all-whitespace-in-a-string-in-python). – Paul Rooney Feb 14 '20 at 03:58