1

I wrote this program and I am having trouble integrating it with another program I wrote. I believe that the way this program is written is causing my difficulty. Any suggestions for a different approach would be much appreciated.

This program takes two strings and determines is they are exact matches, differ by one character, or if they differ by more than one character. If they are exact matches or differ by one character, it returns True; if they differ by more than one character, it returns false.

import string

def similarstrings():
    print "This program will determine whether two strings differ"
    print "by more than one character. It will return True when they"
    print "are the same or differ by one character; otherwise it will"
    print "return False"
    str1 = raw_input("Enter first string:")
    str2 = raw_input("Enter second string:")
    str1 = ' '.join(str1)
    str2 = ' '.join(str2)
    strL1 = string.split(str1, " ")
    strL2 = string.split(str2, " ")
    x = 0
    for i in range(len(strL1)):
        if strL1[i] == strL2[i]:
            x = x + 1
        else:
            x = x
    if x >= len(strL1) - 1:
        print True
    else:
        print False
Atache
  • 169
  • 1
  • 13

2 Answers2

2

This approach only works for a restricted set of inputs such as pointed out by gnibbler - you can try using the built in difflib library to find similarity between strings.

>>> import difflib
>>> s1 = "some string"
>>> s2 = "same string"
>>> difflib.SequenceMatcher(None, s1, s2).ratio()
0.9090909090909091

For more details about the above (or related approaches) you can refer to this stack overflow question

Community
  • 1
  • 1
Ali-Akber Saifee
  • 4,406
  • 1
  • 16
  • 18
1

Not sure what you mean by differing by 1 character. Your code seems to assume that the strings are the same length. If so, this should work

def similarstrings(str1, str2):
    return sum(i != j for i, j in zip(str1, str2)) <= 1
Pavel Anossov
  • 60,842
  • 14
  • 151
  • 124
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • Technically a space is one character... So if he is using that definition, then the code *should* be correct. – xxmbabanexx Feb 26 '13 at 00:13
  • Yeah, this is an unfortunate consequence of how I wrote it. Not necessarily intended. I'm new to programming. Thank you for your help. – Atache Feb 26 '13 at 00:15
  • @Atache, It's probably helpful to create a bunch of examples that cover the various cases you can think of. You can then use those to automatically test your function. – John La Rooy Feb 26 '13 at 00:19