Could someone please explain to me why this won't work? I could always copy the answer, but then I wouldn't learn why this didn't work.
a scrrenshot of the problem, my work, and the error
Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. So "xxcaazz" and "xxbaaz" yields 3, since the "xx", "aa", and "az" substrings appear in the same place in both strings.
def string_match(a, b):
count = 0
if len(a) or len(b) == 0:
return count
else:
if len(a)> len(b):
for n in range(len(a)-2):
if a[n]==b[n]:
count =1
else:
for n in range(len(b)-2):
if b[n]==a[n]:
count =1
return count
Thank you so much!!
I tried using index locations to find matching characters in 2 strings
CodePudding user response:
You should use the length of the shortest string in the loop. So you should switch your condition
from
if len(a) > len(b):
for n in range(len(a)-1):
to
if len(a) < len(b):
for n in range(len(a)-1):
That's for the Index out of range
error, yet as mentionned in the comments there are some other bugs in your code
# first condition
if len(a) == 0 or len(b) == 0:
return 0
Full code
def string_match(a, b):
count = 0
if len(a) == 0 or len(b) == 0:
return 0
if len(a) < len(b):
for n in range(len(a)):
if a[n] == b[n]:
count = 1
else:
for n in range(len(b)):
if a[n] == b[n]:
count = 1
return count
NOTE your code does not answer the given task, take your time to develop a better solution
CodePudding user response:
thank you for your help! I made the following adjustments and the code works!
def string_match(a, b):
count = 0
n=0
if len(a) == 0 or len(b) == 0:
return 0
else:
if len(a) < len(b):
for n in range(len(a)-1):
if a[n:n 2] == b[n:n 2]:
count = 1
else:
for n in range(len(b)-1):
if a[n:n 2] == b[n:n 2]:
count = 1
return count