Count letter differences of two strings

后端 未结 11 704
既然无缘
既然无缘 2020-12-09 17:11

This is the behaviour I want:

a: IGADKYFHARGNYDAA
c: KGADKYFHARGNYEAA
2 difference(s).
11条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-09 17:33

    When looping through one string, make a counter object that identifies the letter you are on at each iteration. Then use this counter as an index to refer to the other sequence.

    a = 'IGADKYFHARGNYDAA'
    b = 'KGADKYFHARGNYEAA'
    
    counter = 0
    differences = 0
    for i in a:
        if i != b[counter]:
            differences += 1
        counter += 1
    

    Here, each time we come across a letter in sequence a that differs from the letter at the same position in sequence b, we add 1 to 'differences'. We then add 1 to the counter before we move onto the next letter.

提交回复
热议问题