Given a number as a string , find the number of contiguous subsequences which recursively add up to 9 | Python 3 program to count substrings with recursive sum equal to 9 ; count = 0 To store result ; Consider every character as beginning of substring ; sum of digits in current substring ; One by one choose every character as an ending character ; Add current digit to sum , if sum becomes multiple of 5 then increment count . Let us do modular arithmetic to avoid overflow for big strings ; Driver Code
def count9s ( number ) : NEW_LINE INDENT n = len ( number ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum = ord ( number [ i ] ) - ord ( '0' ) NEW_LINE if ( number [ i ] == '9' ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT sum = ( sum + ord ( number [ j ] ) - ord ( '0' ) ) % 9 NEW_LINE if ( sum == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( count9s ( "4189" ) ) NEW_LINE print ( count9s ( "1809" ) ) NEW_LINE DEDENT