简体   繁体   中英

How can I compare 2 words and count the strings?

Can somebody please help me with my code to compare 2 words and then count the string difference? Now my code is generating a wrong difference count. It seems like it is counting too much. I checked if my variable is correct and it was.

def difference(word_one, word_two):
    count = 0
    for letter in range(6):
        if word_one[letter] == word_two[letter]:
            count += 1
            print(letter, "letter is right.")
            return count

Update for my code but still some how not working. some time when I count the correct letter they don't match up like this.

BETTER Password incorrect 5/6 correct BASHER

def correct_letter(word_one, word_one):
    count = 0
    for letter in range(6):
        if word_one[letter] != word_two[letter]:
            count += 1
    print(letter, "out of 6 letter is right.")
    return count

Just another suggestion:

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

This has the advantage of not requiring word_one and word_two be of the same length, as well as any efficiency gains you might get from zip and sum .

You should of course use

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

if you want to find the similarities between two strings rather than the difference

def strcmp(word_one, word_two):
    count = 0
    i = j = 0
    while i < len(word_one) and j < len(word_two):
        if word_one[i] != word_two[j]:
            count += 1
        i += 1
        j += 1

    while i < len(word_one):
        count += 1
        i += 1

    while j < len(word_two):
        count += 1
        j += 1

    return count

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM