Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #17851

Re: How to check for single character change in a string?

From Roy Smith <roy@panix.com>
Newsgroups comp.lang.python
Subject Re: How to check for single character change in a string?
Date 2011-12-24 10:57 -0500
Organization PANIX Public Access Internet and UNIX, NYC
Message-ID <roy-AAAEEA.10571424122011@news.panix.com> (permalink)
References <th7hs8-one.ln1@chris.zbmc.eu>

Show all headers | View raw


In article <th7hs8-one.ln1@chris.zbmc.eu>, tinnews@isbd.co.uk wrote:

> Can anyone suggest a simple/easy way to count how many characters have
> changed in a string?

Depending on exactly how you define "changed", you're probably talking 
about either Hamming Distance or Levenshtein Distance.  I would start 
with the wikipedia articles on both those topics and explore from there.

There are python packages for computing many of these metrics.  For 
example, http://pypi.python.org/pypi/python-Levenshtein/

> Is there any simpler/neater way than just a for loop running through
> both strings and counting non-matching characters?

If you don't care about insertions and deletions (and it sounds like you 
don't), then this is the way to do it.  It's O(n), and you're not going 
to get any better than that.  It's a one-liner in python:

>>> s1 = 'abcdefg'
>>> s2 = 'abcdekk'

>>> len([x for x in zip(s1, s2) if x[0] != x[1]])
2

But go read the wikipedia articles.  Computing distance between 
sequences is an interesting, important, and well-studied topic.  It's 
worth exploring a bit.

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

How to check for single character change in a string? tinnews@isbd.co.uk - 2011-12-24 15:26 +0000
  Re: How to check for single character change in a string? Roy Smith <roy@panix.com> - 2011-12-24 10:57 -0500
    Re: How to check for single character change in a string? Roy Smith <roy@panix.com> - 2011-12-24 11:10 -0500
      Re: How to check for single character change in a string? Arnaud Delobelle <arnodel@gmail.com> - 2011-12-24 17:09 +0000
        Re: How to check for single character change in a string? Rick Johnson <rantingrickjohnson@gmail.com> - 2011-12-24 10:22 -0800
      Re: How to check for single character change in a string? tinnews@isbd.co.uk - 2011-12-26 22:37 +0000
  Re: How to check for single character change in a string? Ian Kelly <ian.g.kelly@gmail.com> - 2011-12-24 08:57 -0700

csiph-web