0

here is my code:

def similarStrings(str1,str2):

 lenth=len(str1)
 count=0
 i=0

 while (count<lenth):
     if str1[count]==str2[count]:
         i=i+1
     else:
         i=i


 if i>=length-1:
    return True
 else:
    return False

my expectation was that it should return something....but when I run it, there is nothing appears on the window. I was doing the compare of two strings, if there is less than one character differs, it should returns true. when there are more than one difference character, it should returns false. could someone help me with my code?

6
  • 2
    How are you calling the similarStrings function? Are you calling it? What are you doing with the output? Commented Apr 15, 2014 at 23:19
  • 4
    You never increment count so it is an infinite loop with while Commented Apr 15, 2014 at 23:21
  • on the top of the window there is a button called run. when I run that, In the main window, I typed in similarStrings('asdf','asdd') for testing, and I get nothing when I press enter..... Commented Apr 15, 2014 at 23:22
  • @dawg thank you so much! what if the two string has difference size and I still want to compare them? Commented Apr 15, 2014 at 23:26
  • 1
    Depends on your use case. Look at Levenshtein Distance or difflib Commented Apr 15, 2014 at 23:33

4 Answers 4

3
+200

You are never adding anything to count, so it's basically like calling while 0 < 1:.

At the end of your while loop, add count+=1. Change your code to this:

def similarStrings(str1,str2):

 length=len(str1)
 count=0
 i=0

 while (count<length):
     if str1[count]==str2[count]:
         i=i+1
     else:
         i=i
     count+=1


 if i>=length-1:
    return True
 else:
    return False
Sign up to request clarification or add additional context in comments.

2 Comments

Please correct to variable name "length". However this solution don't seem to be good because if str1 is bigger than str2 """if str1[count]==str2[count]:""" will raise the error:: "IndexError: string index out of range".
This is the OP's version of the code with his specified error omitted
1

As I stated in my comments, your algorithm does not work because you do not increment count in the while loop; while (count<lenth) will always be True and you therefor have an infinite loop. Similar to while True.

You asked how to compare two strings when one might be longer than the other. There are many ways, but one classic algorithm is the Levenshtein Distance. If the strings are the same, it returns 0. Any amount greater than 0 is the number of edits to get the to get one string to be the same as the other.

Here is the Rosetta Code version of Levenshtein distance:

def LevDist(s1,s2):
    if len(s1) > len(s2):
        s1,s2 = s2,s1
    distances = range(len(s1) + 1)
    for index2,char2 in enumerate(s2):
        newDistances = [index2+1]
        for index1,char1 in enumerate(s1):
            if char1 == char2:
                newDistances.append(distances[index1])
            else:
                newDistances.append(1 + min((distances[index1],
                                             distances[index1+1],
                                             newDistances[-1])))
        distances = newDistances
    return distances[-1]

Testing it:

>>> LevDist('kitten', 'kitten')
0
>>> LevDist('kittens', 'kitten')  
1
>>> LevDist('kitten', 'cat')  
5

Another method is to use the tools in difflib.

Good luck.

2 Comments

I think your code may be complicated a little bit vis-a-vis the question.
@elhoucine: I disagree. Levenshtein Distance is a straightforward way to compare strings of different lengths (clearly what he is trying to do) and difflib is part of the Python distribution.
0

There are some issues in your code:

1- You have to increment count.

2- You are setting different names to the same variable "lenth" / "length".

3- str1[count]==str2[count]: will raise error if str1 is bigger than str2 (index out of range).

However, if you want to check if the two strings are similar you may just use:

if str1 == str2:
   return something

Otherwise let me know what do you want to do exactly.

Comments

0

Nothing appears when you run your program because it runs in an infinite loop.

The while (count<lenth): statement tells python to keep running while count is less than "lenth", but since the value of count never changes, this is always true, and python continues running endlessly.

It's rare that you actually need indexes or counters like this in python. You fix it by getting rid of the index by using a for loop, like so:

def similarStrings(str1, str2):
    length = len(str1)
    i = 0 

    for char1, char2 in zip(str1, str2):
        if char1 == char2:
            i = i+1

    if i >= length-1:
        return True
    else:
        return False

I'd rewrite the function like so though:

def similarStrings(str1, str2, difference=1):
    from itertools import izip_longest
    return sum(
        char1 != char2
        for char1, char2 in izip_longest(str1, str2)
    ) <= difference

I wrote a test suite, of sorts:

def test(s1, s2):
    if similarStrings(s1, s2):
        print 'SIMILAR:'
    else:
        print 'NOT SIMILAR:'

    print '   ', s1
    print '   ', s2

def main():
    test('', '')
    test('abc', 'abc')
    test('abcd', 'abc')
    test('abc', 'abcd')
    test('abcd', 'abce')
    test('abcd', 'abcee')
    test('abcdd', 'abce')
    test('abcdd', 'abcee')

if __name__ == '__main__':
    exit(main())

Which gave me these results, using my final implementation:

SIMILAR:


SIMILAR:
    abc
    abc
SIMILAR:
    abcd
    abc
SIMILAR:
    abc
    abcd
SIMILAR:
    abcd
    abce
NOT SIMILAR:
    abcd
    abcee
NOT SIMILAR:
    abcdd
    abce
NOT SIMILAR:
    abcdd
    abcee

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.