user3029969
user3029969

Reputation: 127

How many letter were changed in string

Hello I am fairly new at programming,

I would like to know is there a function or a method that allows us to find out how many letters have been changed in a string..

example:

input:

"Cold"

output:

"Hold"

Hence only 1 letter was changed

or the example:

input:

"Deer"

output:

"Dial"

Hence 3 letters were changed

Upvotes: 0

Views: 153

Answers (4)

Overclock
Overclock

Reputation: 44

Use the itertools library as follows (Python 3.x)

from itertools import zip_longest
def change_count(string1, string2):
    count = 0
    for i, (char1, char2) in enumerate(zip_longest(string1, string2)):
        if char1 != char2:
            count = count + 1
    return count        
string1 = input("Enter one string: ")
string2 = input("Enter another string: ")
changed = change_count(string1, string2)
print("Times changed: ", changed)

Upvotes: 2

loopbackbee
loopbackbee

Reputation: 23332

If you don't need to consider character insertions or deletions, the problem is reduced to simply counting the number of characters that are different between the strings.

Since you're new to programming, a imperative-style program would be:

def differences(string1,string2):
    i=0
    different=0
    for i in range(len(string1)):
        if string1[i]!=string2[i]:
            different= different+1
    return different

something slightly more pythonic would be:

def differences(string1,string2):
    different=0
    for a,b in zip(string1,string2):
        if a!=b:
            different+= 1
    return different

or, if you want to go fully functional:

def differences(string1,string2):
    return sum(map(lambda (x,y):x!=y, zip(string1,string2)))

which, as @DSM suggested, is equivalent to the more readable generator expression:

def differences(string1,string2):
    return sum(x != y for x,y in zip(string1, string2))

Upvotes: 2

AaronB
AaronB

Reputation: 306

Check out the difflib library, particularly then ndiff method. Note: this is kind of overkill for the required job, but it is really great for seeing the differences between two files (you can see which are new, which are changed, etc etc)

word1 = "Cold"
word2 = "Waldo"
i = 0
differences = difflib.ndiff(word1, word2)
for line in differences:
    if line[0] is not " ":
        i += 1
print(i)

Upvotes: 0

jchysk
jchysk

Reputation: 1588

I spoke too soon. First result googling:

https://pypi.python.org/pypi/python-Levenshtein/

This should be able to measure the minimum number of changes needed to get from one string to another.

Upvotes: 2

Related Questions