Problem

  1. Problem
  2. Figure 2. The Hamming distance between these two strings is 7. Mismatched symbols are colored red.
  3. Given two strings s and t of equal length, the Hamming distance between s and t, denoted dH(s,t), is the number of corresponding symbols that differ in s and t. See Figure 2.
  4. Given: Two DNA strings s and t of equal length (not exceeding 1 kbp).
  5. Return: The Hamming distance dH(s,t).

汉明距离计算

image.png
问题:
input: 对于给定的一对sequence(长度相等)
output: 两条序列的汉明距离

  1. # input
  2. GAGCCTACTAACGGGAT
  3. CATCGTAATGACGGCCT
  4. # output
  5. 7

solution -1

  1. def hm_dis(s1, s2):
  2. return sum(e1 != e2 for e1, e2 in zip(s1, s2))
  3. def main():
  4. s1 = "GAGCCTACTAACGGGAT"
  5. s2 = "CATCGTAATGACGGCCT"
  6. print(hm_dis(s1, s2))
  7. if __name__ == '__main__':
  8. main()

solution-2

由于工作的时候会用到,且需要快速运行,补一个cython版本

  1. cpdef int hm_dis(str s1, str s2):
  2. cdef str e1
  3. cdef str e2
  4. cdef int dis = 0
  5. cdef int loc = 0
  6. for e1 in s1:
  7. e2 = s2[loc]
  8. loc = loc + 1
  9. if e1 != e2:
  10. dis += 1
  11. #end-if
  12. #end-for
  13. return dis

solution-3

Golang版本

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. //
  6. func hm(s1_p, s2_p *string) int {
  7. s1, s2 := *s1_p, *s2_p
  8. if len(s1) != len(s2){
  9. panic("length error")
  10. }
  11. dis := 0
  12. for i := 0; i < len(s1); i++ {
  13. if s1[i] != s2[i] {
  14. dis++
  15. }
  16. }
  17. return dis
  18. }
  19. func main() {
  20. seq1 := "GAGCCTACTAACGGGAT"
  21. seq2 := "CATCGTAATGACGGCCT"
  22. d := hm(&seq1, &seq2)
  23. fmt.Println(d)
  24. }