Advertisement
Guest User

Untitled

a guest
Jun 26th, 2019
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1.  
  2.  
  3. def hamming_distance(name_A, name_B):
  4. count=0
  5. for i in range (len(name_A)):
  6. if name_A[i]!= name_B[i]:
  7. count +=1
  8. return count
  9.  
  10. """ This function calculates and return the Hamming Distance between name_A and name_B"""
  11.  
  12. def name_distance(name_A, name_B):
  13. list1=list(name_A)
  14. list2=list(name_B)
  15. if len(name_A)>len(name_B):
  16. min_array = [] #holds all hamming distances
  17. diffs = 0 #the hamming distance at each iteration
  18. #loops through number of times comparisons should be made,
  19. for i in range (len(name_A)-len(name_B)+1):
  20. #compares the index of strings and record hamming distance
  21. for j in range (len(name_B)):
  22. if list1[j]!= list2[j]:
  23. diffs +=1
  24. #pops the first letter of string with longer length so that correct comparison can be made
  25. list1.pop(0)
  26. #adds the hamming distance to array
  27. min_array.append(diffs)
  28. #resets hamming distance
  29. diffs=0
  30.  
  31. alength = len(name_A)
  32. blength = len(name_B)
  33. #gets the smallest hamming distance
  34. diffs = min(min_array)
  35. return diffs + alength - blength
  36.  
  37. if len(name_B)>len(name_A):
  38. min_array = []
  39. diffs = 0
  40. for i in range (len(name_B)-len(name_A)+1):
  41. for j in range (len(name_A)):
  42. if list1[j]!= list2[j]:
  43. diffs +=1
  44. list1.pop(0)
  45. min_array.append(diffs)
  46. diffs=0
  47. alength = len(name_A)
  48. blength = len(name_B)
  49. diffs = min(min_array)
  50. return diffs + blength - alength
  51.  
  52. """This function calculates and return the distance between name_A and name_B where these names may be different length. """
  53.  
  54. def get_name_lists(file_name):
  55. with open(file_name, 'r') as fr:
  56. return [name[:-1] for name in fr]
  57.  
  58. def name_matching(filename, target, k):
  59. ret_list = []#holding all the names that would be returned
  60. for i in get_name_lists(filename):#all the names from the textfile
  61. if name_distance(target,i) < k: #checking if the distance is less than k
  62. ret_list.append(i)# if it is, add it to the list returned
  63. return ret_list
  64.  
  65. """This function loads in a list of names from a file, compares the target name to each name, and returns a list of all names within a distance of k from the target name"""
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement