Last active
August 29, 2015 14:11
-
-
Save craigpalermo/afd662b2dcf81dd936ec to your computer and use it in GitHub Desktop.
Calculate the level of similarity between two strings, on a scale from 0 to 1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Credit to sissi_lauty for this algorithm | |
Original: http://stackoverflow.com/a/15077476 | |
""" | |
from math import sqrt | |
def similarity(x, y): | |
# find length of shorter of the two strings | |
n=min(len(x), len(y)) | |
common=0 | |
# for 0 to n characters, check if characters x[i] and y[i] are the same | |
for i in range(n): | |
if (x[i]==y[i]): | |
# add 1 to number of characters from 0 to n in common | |
common+=1 | |
# calcluate similarity between x and y using number of corresponding characters | |
return common/sqrt(len(x)*len(y)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment