Reputation: 394
I have a problem for class where I need to compare strings ie. 'truck' vs 'trunk' and return the FIRST position in which the strings differ. I have managed to solve the initial part but I run into trouble when I encounter strings of different lengths ie. 'truck' vs 'trucks'. I've tried a few different methods before deleting and going back to square 1 so I'm hoping to get some advice here. Any help would be greatly appreciated. My current code is below.
IDENTICAL = -1
def singleline_diff(line1, line2):
short = min(len(line1),len(line2))
for i in range(0,short):
if line1[i] == line2[i]:
continue
else:
return i
else:
return IDENTICAL
word1 = 'truck'
word2 = 'trunk'
prob1 = singleline_diff(word1, word2)
print(prob1)
Upvotes: 0
Views: 89
Reputation: 9197
you can use zip + enumerate.
zip combines 2 iterables like lists or strings. If you loop through it you get pairs of one character of word1 in a tupel with the character on the same position in word2.
enumerate returns the index of the current loop.
since return stops all activities you can use that to return the index (from enumerate) once the tupel w
(which comes from zip()
has a different character on position 0 and 1
def singleline_diff(word1, word2):
word1 = word1.ljust(len(word2))
word2 = word2.ljust(len(word1))
for i,w in enumerate(zip(word1, word2)):
if w[0] != w[1]:
return i
return "Identical"
word1 = 'truck'
word2 = 'trucks'
print(singleline_diff(word1, word2))
Upvotes: 1
Reputation: 8101
You can simply return IDENTICAL if line1==line2
evaluates to true. If there lengths are uneven and no differences are found, just return short
.
def singleline_diff(line1, line2):
if line1 == line2:
return IDENTICAL
short = min(len(line1),len(line2))
for i in range(0,short):
if line1[i] == line2[i]:
continue
else:
return i
return short
Upvotes: 0