0

What are efficient ways to search for substrings in strings? - Are there specific functions built in python we can use? - Can we convert them to lists then access elements in the list? - Can we use for loops to search through individual elements? - Is there one generally accepted method by Python programmers?

It would be helpful to understand the different strategies to help me solve the following problem:

Return the number of times that the string "code" appears anywhere in the given string, except we'll accept any letter for the 'd', so "cope" and "cooe" count.

count_code('aaacodebbb') → 1
count_code('codexxcode') → 2
count_code('cozexxcope') → 2

4 Answers 4

2

You can use regex:

>>> import re
def count(s):
    return sum(1 for m in re.finditer(r'co.e', s))
... 
>>> count('aaacodebbb')
1
>>> count('codexxcode')
2
>>> count('cozexxcope')
2

Here . matches any character, if you only want to match alphabets then use r'co[a-zA-Z]e'.

Sign up to request clarification or add additional context in comments.

6 Comments

How could this be done without using a external library?
re is part of the python standard library, so it is no more external than sys or os.
as per @robertking s answer -> 'codexxcode'.count("code") no regex or modules at all!
I'm curious that why do you use "sum(...)" instead of len(...) ?
@Tarzan What's the point of creating a list in memory when only count is required as output.
|
0

Using regular expression would work for this-

import re
regex = re.compile(r'co[a-z]e')
li = regex.findall("cozexxcope")           #Output: ['coze', 'cope']

Count can be found be the len(li).

Comments

0
    def count_code(str):
      count = 0 #set count to 0 initially
        #For loops number of times that there are chars
      for i in range(len(str)-1): 
         #looks for "co", [any char] and "e"
        if str[i:i+2] == "co" and str[i+3:i+4] == "e":  
            #add up the number of times this happens and return it
          count+= 1 
    return count

1 Comment

In addition to providing code, you should explain to OP what/how this code works and why you took this approach.
0

This was my solution:

def count_code(str):
  count = 0
  for i in range(0, len(str)-3):
    if str[i] == "c" and str[i+1] == "o" and str[i+3] == "e":
      count = count + 1
  return count

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.