I have to write a function that takes a string as argument and compair this string to two other strings and return the string most similar and the number of differences.
def func("LUMB"):
lst=["JIBM", "NUNE", "NUMB"]
should return:
("NUMB",1)
I have tried:
def f(word):
lst=["JIBM", "NUNE", "NUMB"]
for i in lst:
d=k(word, lst)
return differences
for n in d:
print min(sum(n))
where:
def k(word1, word2):
L=[]
for w in range(len(word1)):
if word1[w] != word2[w]:
L.append(1)
else:
L.append(0)
return L
so that i get a list of eg, [1,0,0,0] if word1="NUMB" and word2="LUMB"
The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.
Using String. equals() :In Java, string equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are same then it returns true.
The return value from strcmp is 0 if the two strings are equal, less than 0 if str1 compares less than str2 , and greater than 0 if str1 compares greater than str2 . No other assumptions should be made about the value returned by strcmp .
The compareTo() method compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings.
Looks like Shawn Chin has provided the best solution, but if you're prevented from using non-builtin modules, it seems like get_close_matches
from difflib
might help:
import difflib
difflib.get_close_matches("LUMB", ["JIBM", "NUNE", "NUMB"], 1)
The number of differences can be gotten using the get_opcodes
method of SequenceMatcher
and working with its return value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With