Search code examples
pythonedit-distance

How to check how many characters a variable has in common with another variable


If I have two variables, and I want to see how many characters they have in common, what would I do to reach a number of how many were wrong? for example:

a = "word"
b = "wind"
a - b = 2

is there a way to do this or to make what is above work?

Edit: it should also take into account order when calculating

Edit2: All these should turn out as shown bellow

a = bird
b = word
<program to find answer> 2


a = book
b = look
<program to find answer> 3


a = boat
b = obee
<program to find answer> 0

a = fizz
b = faze
<program to find answer> 2

Solution

  • This might not apply for all cases, but if you would like to compare characters you can use set:

    a = "word"
    b = "wind"
    
    diff = set.intersection(set(a),set(b))
    print(len(diff))
    >> 2
    

    This ignores sequences as you are grouping them into a set of unique characters.

    Another interesting Python standard module library you can use is difflib.

    from difflib import Differ
    
    d = Differ()
    
    a = "word"
    b = "wind"
    
    [i for i in d.compare(a,b) if i.startswith('-')]
    >>['- o', '- r']
    

    difflib essentially provides methods for you to compare sequences such as strings. From the Differ object above, you can compare 2 strings and identify characters which are added or removed to track changes from the string a to string b. In the example given, a list comprehension is used to filter out characters which are removed from a to b, you can also check characters that start with + for characters that are added.

    [i for i in d.compare(a,b) if i.startswith('+')]
    >>['+ i', '+ n']
    

    Or characters common to both sequence addressing

    How to check how many characters a variable has in common with another variable

    common = [i for i in d.compare(a,b) if i.startswith('  ')]
    print(common, len(common))
    >> ['  w', '  d'] 2
    

    You can read more about the Differ object here