Write a function nearlyEqual to test whether two strings are nearly equal. Two strings string1 and string2 are nearly equal when string1 can be generated by a single mutation on string2. The fundtion should return a boolean (True or False).
"""Returns True if the two strings only differ by one character.
>>> nearlyEqual('python', 'perl')
False
>>> nearlyEqual('perl', 'pearl')
True
>>> nearlyEqual('python', 'jython')
True
>>> nearlyEqual('man', 'woman')
False
"""
def nearlyEqual(string1, string2):
string1 = input('First Word')
string2 = input('Second Word')
if string1 == string2:
print (True)
else:
print (False)
return nearlyEqual(string1,string2)
print (nearlyEqual(string1,string2))
string1 = ()
string2 = ()
print, nearlyEqual(string1, string2)
Return True if there are 2 strings that only differ by 1 character in the same index, otherwise return False. Example 1: Input: dict = ["abcd","acbd", "aacd"] Output: true Output: Strings "abcd" and "aacd" differ only by one character in the index 1.
How to Compare Strings Using the <= Operator. The <= operator checks if one string is less than or equal to another string. Recall that this operator checks for two things – if one string is less or if both strings are the same – and would return True if either is true. We got True because both strings are equal.
Python String comparison can be performed using equality (==) and comparison (<, >, !=
Interesting question. A natural approach would be to use a full-fledged Levenshtein distance (AKA "edit distance") and ensure it equals 1. However, for the special case of 1, you can do better.
If the two strings are the same length, you clearly need to check that they differ in just one spot...:
if len(string1) == len(string2):
count_diffs = 0
for a, b in zip(string1, string2):
if a!=b:
if count_diffs: return False
count_diffs += 1
return True
If the length difference is above 1, then the result is clearly False.
The interesting case comes when the difference is exactly one -- in which case you must check if the longer string can be made into the shorter one by dropping exactly one character.
if abs(len(string1) - len(string2)) > 1: return False
if len(string1) < len(string2):
string1, string2 = string2, string1
Here I'm swapping the strings, if needed, to ensure string1 is longer by exactly one character.
Now, we want to iterate independently on each string:
it1 = iter(string1)
it2 = iter(string2)
count_diffs = 0
c1 = next(it1, None)
c2 = next(it2, None)
while True:
if c1 != c2:
if count_diffs: return False
count_diffs = 1
c1 = next(it1)
else:
try:
c1 = next(it1)
c2 = next(it2)
except StopIteration: return True
I'll leave it up to you how to put together these snippets to make the overall function work as intended -- so you can show at least some understanding of Python, as you're being asked to display!-)
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