As you clarified, you want to find difference between two strings by characters with their positions, you can do the following:
- Iterate over your list one by one.
- For each word in the list, compare it with the supplied string character by character.
- If a character from one doesn't match with the other, increment the diff counter.
- If difference becomes greater than needed difference, return
False
, else return True
.
- Keep in mind that 2 strings in comparison can be of different lengths. Take that into account too while calculating them.
Snippet:
def isSame(str_list,s,diff_offset):
s_len = len(s)
for each_s in str_list:
diff = abs(len(each_s) - s_len) # initialize with difference of string length
length = min(len(each_s),s_len)
for i in range(0,length):
if s[i] != each_s[i]:
diff = diff + 1
if diff > diff_offset:
return False # if difference is more than required, then return false
return True
print(isSame(["ccat","hpat","ppat"], "ppat", 2))
print(isSame(["ccat","hpat","ppatru"], "ppat", 2))
print(isSame(["ccat","hpat","that"], "ppat", 1))
Update:
As per the problem statement, if lengths are not same, just return False before beginning to compare strings char by char.
def isSame(str_list,s,diff_offset):
s_len = len(s)
for each_s in str_list:
if len(each_s) != s_len:
return False
diff = 0
for i in range(0,s_len):
if s[i] != each_s[i]:
diff = diff + 1
if diff > diff_offset:
return False # if difference is more than required, then return false
return True
print(isSame(["ccat","hpat","ppat"], "ppat", 2))
print(isSame(["ccat","hpat","ppatru"], "ppat", 2))
print(isSame(["ccat","hpat","that"], "ppat", 1))