0

So, I need to figure out a program that when you input 2 different strings of the same length it will return NOT print the number of differences between the two strings. The order of the characters matters as well.

For example if you input ("abcdef", "aabccf") it should return 4.

("abcdef", "accddf") should return 2.

All I have so far is:

def differencecount ( A, B): counter = 0 str1 = list (A) str2 = list (B) for letter in str1: if letter == str2: counter = counter + 1 return counter

All this does is return 0 though so I feel like I'm missing something.

2
  • what happens if x and y are different lengths? what is the expected output?
    – ml-moron
    Commented May 10, 2016 at 0:19
  • I was thinking of adding len (x) = len (y) to make sure they're equal in length. If they aren't equal in length I'll probably add a print 'Please enter strings of equal length' at the end.
    – Pichu2016
    Commented May 10, 2016 at 0:21

3 Answers 3

3

I would use

def difference(word_one, word_two):
    return sum(l1 != l2 for l1, l2 in zip(word_one, word_two))

Which works like

>>> difference('abcdef', 'abcdef')
0
>>> difference('abcdef', 'abcabc')
3
1
  • 1
    Not sure it's a good idea to be doing this person's homework for them :/ Commented May 10, 2016 at 0:17
1

You can zip the strings together and then count how many different pairs there are:

def chardifferencecounter(x, y):
    return len([1 for c1, c2 in zip(x, y) if c1 != c2])

>>> chardifferencecounter('abcdef', 'aabccf')
4
>>> chardifferencecounter('abcdef', 'accddf')
2

Explanation:

Zipping the strings together produces this:

>>> s1 = 'abcdef'
>>> s2 = 'aabccf'
>>> zip(s1, s2)
[('a', 'a'), ('b', 'a'), ('c', 'b'), ('d', 'c'), ('e', 'c'), ('f', 'f')]

so it takes a character from the same position in each string and pairs them together. So you just need to count how many pairs are different. That can be done using a list comprehension to create a list with those pairs that are the same filtered out, and then get the length of that list.

1
  • 2
    @Pichu2016: didn't I already explain that in the answer? Check the documentation for more details.
    – mhawke
    Commented May 10, 2016 at 0:29
0

Just for a different look here is a solution that doesn't use zip or enumerate:

def chardifferencecounter(x,y):
    if len(x) != len(y):
        raise Exception('Please enter strings of equal length')
    return sum(x[i] != y[i] for i in range(len(x)))

Note that this solution also raises an exception when x and y are of different lengths, which is what you wanted in your comment.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.