Reputation: 19
I have been trying to solve this past final exam question. I think I am getting close, but due to the unequal lengths of the two strings, I am getting an index out of range error which i can't figure out...
How would you try solve this question? How can I solve the IndexError?
Thank you in advance :D
def print_first_difference(string1, string2):
""" Solving the first difference between 2 words, and print the position. """
for letter in range(len(string1)):
if string1[letter] != string2[letter]:
print("Strings differ at postion {}".format(letter + 1))
break
else:
print("Strings are identical")
print_first_difference("abcd", "abde")
print_first_difference("abcdef", "abcdef")
print_first_difference("abcdef", "abc")
print_first_difference("abc", "abcdef")
Output:
Strings differ at postion 3
Strings are identical
IndexError: string index out of range
Upvotes: 1
Views: 1783
Reputation: 23098
Encapsulate your test in a try/catch
in case of IndexError
, which means that the second string is shorter than the first one, which means the two strings differ.
for letter in range(len(string1)):
try:
if string1[letter] != string2[letter]:
print("Strings differ at postion {}".format(letter + 1))
break
except IndexError:
print("Strings differ at postion {}".format(letter + 1))
break
Edit: have you thought about the case where string1
is shorter than string2
? I think your algorithm will assume both strings are identical.
Upvotes: 3
Reputation: 31
My solution would be:
def print_first_difference(string1, string2):
aggr_strings = zip(string1, string2)
for index, tup in enumerate(aggr_strings):
if tup[0] != tup[1]:
print("Strings differ at position " + str(index))
break
else:
if len(aggr_strings) != len(max(string1, string2)):
print("Strings differ at position " + str(len(min(string1, string2))))
else:
print("Strings are identical")
Upvotes: 1