# comparing parts of strings: help please

 Justin Red · November 21, 2014 Here is the problem...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. string_match('xxcaazz', 'xxbaaz') ? 3string_match('abc', 'abc') ? 2string_match('abc', 'axc') ? 0Here is my code that returns a "string index out of range" error...def string_match(a, b):    min = 0    count = 0    if len(a) >= len(b):        min = len(a)    else:        min = len(b)    for i in range(min-1):        if (a + a[i+1]) == (b + b[i+1]):            count += 1    return countHere is the modified code that works...def string_match(a, b):    lesser = 0    count = 0    if len(a) >= len(b):        lesser = len(a)    else:        lesser = len(b)    for i in range(lesser-1):        if a[i:i+2] == b[i:i+2]:            count += 1    return countHow are the 2 "if" statements not equal?  Why is the one in the first example wrong?

## Replies

 Justin Red · November 22, 2014 Thanks, VT.Off now to learn those predefined functions! Vaggelis Theodoridis · November 22, 2014 Btw you can do minimum = min(len(a), len(b)) less lines of code (and also it is not good to use variable names that are predefined words/functions like min) Justin Red · November 22, 2014 That's the second time the post has changed what I actually typed.I am spacing this to show what I typed...i f  ( a  + a )...turned into...if (a+a[i+1])and changed to italics.I figured out my problem, though...if len(a) >= len(b): min = len(a)else: min = len(b)the ">=" should have been "<="I broke the first rule. Sorry, Bucky! Justin Red · November 22, 2014 Thanks for the reply VT.the incorrect "if" statement should have looked like this...if (a + a[i+1])  == (b + b[i+1]):if (a + a[i+1]) == (b + b[i+1]):but it still gives the same error message. It seems to check the first and second characters of each string, advancing the starting point each iteration.No? Vaggelis Theodoridis · November 22, 2014 The if statements seem ok.The problem in the first code is that when the "for" loop reaches the last element of the list it checks:a = 'abc'#So the last element is the cif (a + a[i+1]) --> which means 'abc' + ? theres no other element to check c was the last one! It will throw an error! The last position of i=2 cant go to 3!So in the second code it checks it with another way. When we code for example:print (a[1:9999]) and a='abc' it will not throw error, it will stop in the last element and print 'abc' but with the first way it will try to go further from 'abc...'
• 1

## Python

130,888 followers