Jaro and Jaro | Python3 implementation of above approach ; Function to calculate the Jaro Similarity of two s ; If the s are equal ; Length of two s ; Maximum distance upto which matching is allowed ; Count of matches ; Hash for matches ; Traverse through the first ; Check if there is any matches ; If there is a match ; If there is no match ; Number of transpositions ; Count number of occurrences where two characters match but there is a third matched character in between the indices ; Find the next matched character in second ; Return the Jaro Similarity ; Driver code ; Prjaro Similarity of two s
from math import floor , ceil NEW_LINE def jaro_distance ( s1 , s2 ) : NEW_LINE INDENT if ( s1 == s2 ) : NEW_LINE INDENT return 1.0 NEW_LINE DEDENT len1 = len ( s1 ) NEW_LINE len2 = len ( s2 ) NEW_LINE max_dist = floor ( max ( len1 , len2 ) / 2 ) - 1 NEW_LINE match = 0 NEW_LINE hash_s1 = [ 0 ] * len ( s1 ) NEW_LINE hash_s2 = [ 0 ] * len ( s2 ) NEW_LINE for i in range ( len1 ) : NEW_LINE INDENT for j in range ( max ( 0 , i - max_dist ) , min ( len2 , i + max_dist + 1 ) ) : NEW_LINE INDENT if ( s1 [ i ] == s2 [ j ] and hash_s2 [ j ] == 0 ) : NEW_LINE INDENT hash_s1 [ i ] = 1 NEW_LINE hash_s2 [ j ] = 1 NEW_LINE match += 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT if ( match == 0 ) : NEW_LINE INDENT return 0.0 NEW_LINE DEDENT t = 0 NEW_LINE point = 0 NEW_LINE for i in range ( len1 ) : NEW_LINE INDENT if ( hash_s1 [ i ] ) : NEW_LINE INDENT while ( hash_s2 [ point ] == 0 ) : NEW_LINE INDENT point += 1 NEW_LINE DEDENT if ( s1 [ i ] != s2 [ point ] ) : NEW_LINE INDENT point += 1 NEW_LINE t += 1 NEW_LINE DEDENT DEDENT DEDENT t = t // 2 NEW_LINE return ( match / len1 + match / len2 + ( match - t + 1 ) / match ) / 3.0 NEW_LINE DEDENT s1 = " CRATE " NEW_LINE s2 = " TRACE " NEW_LINE print ( round ( jaro_distance ( s1 , s2 ) , 6 ) ) NEW_LINE