Probability of collision between two trucks | Function to calculate total number of accidents ; Function to calculate count of all possible collision ; Size of string ; Stores the count of collisions ; Total number of truck in lane b ; Count total number of collisions while traversing the string a ; Function to calculate the probability of collisions ; Evaluate total outcome that is all the possible accident ; Evaluate favourable outcome i . e . , count of collision of trucks ; Print desired probability ; Driver Code ; Function Call
def count_of_accident ( a , b ) : NEW_LINE INDENT n = len ( a ) NEW_LINE m = len ( b ) NEW_LINE if ( n > m ) : NEW_LINE INDENT return ( m * ( m + 1 ) ) / 2 NEW_LINE DEDENT else : NEW_LINE INDENT return ( ( n * ( n + 1 ) ) / 2 + ( m - n ) * n ) NEW_LINE DEDENT DEDENT def count_of_collision ( a , b ) : NEW_LINE INDENT n = len ( a ) NEW_LINE m = len ( b ) NEW_LINE answer = 0 NEW_LINE count_of_truck_in_lane_b = 0 NEW_LINE for i in range ( 0 , m ) : NEW_LINE INDENT if ( b [ i ] == ' T ' ) : NEW_LINE INDENT count_of_truck_in_lane_b += 1 NEW_LINE DEDENT DEDENT i = 0 NEW_LINE while ( i < m and i < n ) : NEW_LINE INDENT if ( a [ i ] == ' T ' ) : NEW_LINE INDENT answer += count_of_truck_in_lane_b NEW_LINE DEDENT if ( b [ i ] == ' T ' ) : NEW_LINE INDENT count_of_truck_in_lane_b -= 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return answer NEW_LINE DEDENT def findProbability ( a , b ) : NEW_LINE INDENT total_outcome = count_of_accident ( a , b ) ; NEW_LINE favourable_outcome = count_of_collision ( a , b ) ; NEW_LINE print ( favourable_outcome / total_outcome ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " TCCBCTTB " NEW_LINE T = " BTCCBBTT " NEW_LINE findProbability ( S , T ) NEW_LINE DEDENT