john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

find remove remove all

# -*- coding: utf-8 -*-

class Challenges():


    @staticmethod
    def find( target_string, source_string, start_index=0 ):
        """ returns the first index number if the target is in the source string (starting at given index), or -1 if not found
        """
        match_index = -1
        source_length = len( source_string )
        target_length = len( target_string )

        if source_length >= target_length and target_length > 0:

            for i in xrange( start_index, source_length, 1 ):
                if source_string[ i ] ==  target_string[ 0 ]:
                    match_start = i
                    k = 0
                    while i < source_length and k < target_length and source_string[ i ] == target_string[ k ]:
                        i += 1
                        k += 1

                    if k == target_length:
                        match_index = match_start
                        break
        return match_index


    @staticmethod
    def remove( target_string, source_string, start_index=0 ):
        """ returns a string which is the result of the source_string (starting at given index) with the first match of the target_string removed or None if not found
        """
        result = None
        found_index = Challenges.find( target_string, source_string, start_index=start_index)
        if found_index >= 0:
            result_before = source_string[ :found_index ]
            result_after = source_string[ found_index + len( target_string): ]
            result = ''.join( [ result_before , result_after ] )
        return result


    @staticmethod
    def remove_all( target_string, source_string, start_index=0 ):
        """ returns a string which is the result of the source_string (starting at given index) with all matches of the target_string removed or None if not found
        """
        index = start_index
        original = source_string

        intermediate_result = source_string
        while intermediate_result:
            intermediate_result = Challenges.remove( target_string, source_string, start_index=index )
            if intermediate_result:
                source_string = intermediate_result
                print intermediate_result
            else:
                break

        if len( source_string ) < len( original ):
            return source_string        # modified during the operation - name here may be misleading
        else:
             return None

  • « palindromeTransformer
  • find remove remove all tests »

Published

Apr 29, 2013

Category

python

~220 words

Tags

  • all 7
  • find 13
  • python 180
  • remove 16