Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6981683
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T18:11:20+00:00 2026-05-27T18:11:20+00:00

def subStringMatchExact(target, key): if (target.find(key) == -1): return [] else: foundStringAt = [target.find(key)] target

  • 0
def subStringMatchExact(target, key):

    if (target.find(key) == -1):
        return []
    else:
        foundStringAt = [target.find(key)]
        target = target[foundStringAt[0] + len(key):]
        return foundStringAt + subStringMatchExact(target, key)

string = subStringMatchExact("your code works with wrongly correlated coefficients which incorporates more costs", "co") 

print(string)

Current incorrect output:

[5, 22, 9, 19, 14]

I am having trouble summing the length of the substring on the previous recursion step. Like the second element of the list should be 29 instead of 22 as in len(previousSubstring) + len(key) - 1 + len(currentSubstring).

Any ideas to improve my code and/or fix my error too?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T18:11:21+00:00Added an answer on May 27, 2026 at 6:11 pm

    The fast way

    You don’t have to implement your own solution, its already done! Use the finditer function from the re module:

    >>> import re
    >>> s = 'your code works with wrongly correlated coefficients which incorporates more costs'
    >>> matches = re.finditer('co', s)
    >>> positions = [ match.start() for match in matches ]
    >>> positions
    [5, 29, 40, 61, 77]
    

    Your own way

    If you want to make your own implementation (using recursion) you could take advantage of the extra arguments of the str.find function. Lets see what help(str.find) says about it:

    S.find(sub [,start [,end]]) -> int
    
        Return the lowest index in S where substring sub is found,
        such that sub is contained within s[start:end].  Optional
        arguments start and end are interpreted as in slice notation.
    
        Return -1 on failure.
    

    There is an extra argument called start that tells str.find where to start searching the substring. That’s just what we need!

    So, modifying your implementation, we can get a simple, fast and beautiful solution:

    def substring_match_exact(pattern, string, where_should_I_start=0):
        # Save the result in a variable to avoid doing the same thing twice
        pos = string.find(pattern, where_should_I_start)
        if pos == -1:
            # Not found!
            return []
        # No need for an else statement
        return [pos] + substring_match_exact(pattern, string, pos + len(key))
    

    What is the recursion doing here?

    • You’re first searching the substring in the string starting at position 0.
    • If the substring wasn’t found, an empty list is returned [].
    • If the substring was found, it will be returned [pos] plus all the positions where the substring will appear in the string starting at position pos + len(key).

    Using our brand new function

    >>> s = 'your code works with wrongly correlated coefficients which incorporates more costs'
    >>> substring_match_exact('co', s)
    [5, 29, 40, 61, 77]
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

def isBig(x): if x > 4: return 'apple' else: return 'orange' This works: if
def update @album = Album.find(params[:id]) if @album.update_attributes(params[:album]) redirect_to(:action=>'list') else render(:action=>'edit') end end A Rails
def fun1(a): for i in range(len(a)): a[i] = a[i] * a[i] return a
def test4(request): logging.debug(request) logging.debug(request.META['HTTP_REFERER']) return render_to_response('test2/test4.html', context_instance=RequestContext(request)) In the above code can request be
def ExtractViewState(string): m = re.match(__viewstate[^>]+value=\\(\?<Value>[^\]*\), string, re.IGNORECASE) return m.group(0) I think I'm missing something,
def self.get(server) return unless server server = server.to_s if klass = @handlers[server] obj =
def any? if block_given? method_missing(:any?) { |*block_args| yield(*block_args) } else !empty? end end In
def record return unless @supported klasses = profile_options[:formats].map { |f| RubyProf.const_get(#{f.to_s.camelize}Printer) }.compact klasses.each do
def update @user = User.find(params[:id]) if @user.update_attributes(params[:user]) render :action => show end render :template
def _table_(request,id,has_permissions): dict = {} dict.update(get_newdata(request,rid)) return render_to_response('home/_display.html',context_instance=RequestContext(request,{'dict': dict, 'rid' : rid, 'has_permissions' :

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.