q3a(string1, string2)
must be the same length and only one digit must be a different word for string1 and string2 to be true. For example, q3a("bat", "bet")
should be True, q3a('nat', 'ant')
should be False.
That's all for the code we just made, but if string1 or string2 exceeds 5 digits, an index error appears, so I'm asking you a question. You can only use simple loops.
def q3a(string1, string2):
index = 0
while index <= len(string1) and len(string2):
if len(string1) == len(string2):
if string1 == string2:
return True
elif string1 != string2:
while index <= len(string1) and len(string2):
if string1[index] == string2[index]:
index = index + 1
if string1[index] != string2[index]:
index = index + 1
if string1[index] == string2[index]:
return True
else:
return False
elif string1[index] != string2[index]:
index = index + 1
if string1[index] == string2[index]:
index = index + 1
return True
elif string1[index] != string2[index]:
return False
index = index + 1
else:
return False
index = index + 1
Can't we do it this way?
def question(str_1, str_2):
if len(str_1) == len(str_2):
count_not_equal = 0
for match_index in range(len(str_1)):
if str_1[match_index] == str_2[match_index]:
pass
else:
count_not_equal += 1
if count_not_equal == 1:
return True
else:
return False
else:
return False
"""
I guess we can use built-in functions.
The function of zip is ['aa', 'bbb')
and ['a', 'b'], ('a', 'b'), ('a', 'b'), ('a', 'b')]
when you do .
def q3a(string1, string2):
"""True if the number of strings is the same and the character index of each string is not more than one."""
return True if len(string1) == len(string2) and [c1 == c2 for c1, c2 in zip(string1, string2)].count(False) < 2 else False
print(q3a('ant', 'nat')) # False
print(q3a('bat', 'bet')) # True
def q3a(string1, string2):
"""True if the number of strings is the same and the character index of each string is not more than one."""
return True if len(string1) == len(string2) and [string1[i] == string2[i] for i in range(len(string1))].count(False) < 2 else False
print(q3a('ant', 'nat')) # False
print(q3a('bat', 'bet')) # True
scala version.
Scala is as expressive as Python. (Actually, it's better.))
def q3a(s1: String, s2: String): Boolean = if ((s1.length == s2.length) && (for (pair_letter <- s1.zip(s2)) yield {
pair_letter._1 == pair_letter._2
}).count(_ == false) < 2) true else false
q3a("ant", "nat") // false
q3a("bat", "bet") // true
© 2025 OneMinuteCode. All rights reserved.