


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



from collections import Counter
def levenshtein_distance(s1, s2): m = len(s1) n = len(s2) dp = [[0]*(n+1) for _ in range(m+1)]
for i in range(m+1): dp[i][0] = i for j in range(n+1): dp[0][j] = j
for i in range(1, m+1): for j in range(1, n+1): if s1[i-1] == s2[j-1]: cost = 0 else: cost = 1 dp[i][j] = min( dp[i-1][j] + 1, # Deletion dp[i][j-1] + 1, # Insertion dp[i-1][j-1] + cost # Substitution ) return dp[m][n]
dictionary = [ "computer", "science", "python", "language", "machine", "learning", "student", "college", "university", "network", "analysis", "algorithm", "artificial", "intelligence", "database", "software" ]
word_frequency = Counter({
"computer":60, "science":45, "python":70, "language":40, "machine":55, "learning":50, "student":90, "college":65, "university":35, "network":30, "analysis":25, "algorithm":20, "artificial":15, "intelligence":15, "database":18, "software": })
def suggest_word(word): candidates = [] for correct_word in dictionary: distance = levenshtein_distance(word.lower(), correct_word) candidates.append( (correct_word, distance, word_frequency[correct_word]) )
candidates.sort(key=lambda x: (x[1], - x[2])) return candidates[0]
test_words = { "langauge":"language", "machne":"machine", "lernning":"learning", "studnt":"student", "algoritm":"algorithm", "databse":"database", "pythn":"python", "sciense":"science", "softwere":"software", "netwrok":"network" }