Problem

  1. Problem
  2. In DNA strings, symbols 'A' and 'T' are complements of each other, as are 'C' and 'G'.
  3. The reverse complement of a DNA string s is the string sc formed by reversing the symbols of s, then taking the complement of each symbol (e.g., the reverse complement of "GTCA" is "TGAC").
  4. Given: A DNA string s of length at most 1000 bp.
  5. Return: The reverse complement sc of s.

输入: DNA或RNA序列
输出: 反向互补序列

  1. # input:
  2. AAAACCCGGT
  3. # output:
  4. ACCGGGTTTT

solution -1

使用字符串的repalce方法, [::-1]利用索引反转

  1. BASE_DICT = {"A":"t", "T":"a", "G":"c", "C":"g"}
  2. def reverse_complement(seq):
  3. seq_tmp = seq.upper()
  4. for base, base_comp in BASE_DICT.items():
  5. seq_tmp = seq_tmp.replace(base, base_comp)
  6. seq_rev_comp = seq_tmp.upper()[::-1]
  7. return seq_rev_comp
  8. def main():
  9. seq = "AAAACCCGGT"
  10. seq_rev_comp = reverse_complement(seq)
  11. print(seq_rev_comp)
  12. if __name__ == "__main__":
  13. main()

solution -2

碱基转换部分一样,反转部分不一样,利用reversed()函数和str.join()反转字符串,慢

  1. BASE_DICT = {"A":"t", "T":"a", "G":"c", "C":"g"}
  2. def reverse_complement(seq):
  3. seq_tmp = seq.upper()
  4. seq_rev_comp = ""
  5. for base, base_comp in BASE_DICT.items():
  6. seq_tmp = seq_tmp.replace(base, base_comp)
  7. seq_rev_comp = "".join(reversed(seq_tmp.upper()))
  8. return seq_rev_comp
  9. def main():
  10. seq = "AAAACCCGGT"
  11. seq_rev_comp = reverse_complement(seq)
  12. print(seq_rev_comp)
  13. if __name__ == "__main__":
  14. main()

solution -3

Golang实现

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. func rev(s string) string {
  7. r := []rune(s)
  8. for i, j := 0, len(r) - 1; i <= j; i, j = i + 1, j - 1 {
  9. r[i], r[j] = r[j], r[i]
  10. }
  11. return string(r)
  12. }
  13. func com(s string) string {
  14. com_map := map[string]string{"A":"t", "T":"a", "G":"c", "C":"g"}
  15. for k, _ := range com_map {
  16. s = strings.ReplaceAll(s, k, com_map[k])
  17. }
  18. return strings.ToUpper(s)
  19. }
  20. func main() {
  21. seq := "AAAACCCGGT"
  22. seq2 := com(rev(seq))
  23. fmt.Println(seq2)
  24. }