Bum Bum
Bum Bum

Reputation: 49

Counting number of times words appear In strings

I was practicing from coding bat and the question was to find the number of times the word ‘code’ appears in a string, but the letter ‘d’ in ‘code’ can be substituted for any letter. So “code” has count 1, ‘cope’ also 1. I wrote some code but it doesn't work. I don't understand why it doesn't work. The function returns 0 for every input. Here is a link to what I tried https://codingbat.com/prob/p186048

def count_code(str):
     count = 0
     str = str.lower()
     for x in str:
         if x == ‘c’ and str.find(x) + 1 == “o” and str.find(x) + 3 == “e”:
            count += 1
     return count 

Upvotes: 2

Views: 313

Answers (4)

Sumit
Sumit

Reputation: 71

Use regular expression for this, It's fast, convenient and short code.

#CODE
import re

#findall() Returns a list containing all matches
str="cole code cope"
result = re.findall("co.e", str) 
print(len(result))
#END

Hope this will fulfill your requirement.

Upvotes: 0

user12690225
user12690225

Reputation:

As Tim mentioned I would go for regular expressions in such tasks however, if you need a simpler way(not the most efficient but one way to do it):

import string


text = 'elephant code joke cole coke man'
total = 0
for letter in string.ascii_lowercase:
    total += text.count(f'co{letter}e')
print(f'{total}')

Note that in your solution attempt, there is this:

for x in str:

Apart from the fact that you should avoid name collisions str in that case, for a text of size 1000 characters, you'll be doing 1000 iterations, reduced to 26 iterations(letters of the alphabet) using this approach.

Upvotes: 3

Prune
Prune

Reputation: 77880

You've confused the index and the contents of the characters:

str.find(x) + 1 == ‘o’

This can never be true: your find call will return the position of the first such character in the string. You add 1 to that index. How do you imagine that this integer sum can be equal to the character 'o'? An integer and a character cannot be equal.

You need to back up and redesign your logic. When you do that, see this lovely reference for debugging help. You need to learn how to trace problems in your own code.

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522626

I would use re.findall here, and then just take the count of how many matches were found:

inp = "blah code blah cole blah core blah"
print(len(re.findall(r'\bco[a-z]e\b', inp)))    # prints 3

The regex pattern used here is \bco[a-z]e\b, which matches any word code, where the third letter d can actually be any letter.

Upvotes: 1

Related Questions