comapring two strings
Paul McGuire
ptmcg at austin.rr._bogus_.com
Fri May 19 00:23:04 EDT 2006
"manstey" <manstey at csu.edu.au> wrote in message
news:1147992792.038103.151360 at j55g2000cwa.googlegroups.com...
> Hi,
>
> Is there a clever way to see if two strings of the same length vary by
> only one character, and what the character is in both strings.
>
> E.g. str1=yaqtil str2=yaqtel
>
> they differ at str1[4] and the difference is ('i','e')
>
>>> def offByNoMoreThanOneCharacter(a,b):
... return len(a)==len(b) and sum(map(lambda (x,y): x==y, zip(a,b))) >=
len(a)-1
...
>>> offByNoMoreThanOneCharacter("abc","abd")
True
>>> offByNoMoreThanOneCharacter("abc","axd")
False
>>> offByNoMoreThanOneCharacter("yaqtil","yaqtel")
True
>>> offByNoMoreThanOneCharacter("yiqtol","yaqtel")
False
This takes advantage of the Python convention that True evaluates to 1 and
False evaluates to 0.
-- Paul
More information about the Python-list
mailing list