Open hic003cih opened 4 years ago
原版
package dna
import (
"errors"
"strings"
)
// Histogram is a mapping from nucleotide to its count in given DNA.
// Choose a suitable data type.
type Histogram map[rune]uint
// DNA is a list of nucleotides. Choose a suitable data type.
type DNA string
// Counts generates a histogram of valid nucleotides in the given DNA.
// Returns an error if d contains an invalid nucleotide.
///
// Counts is a method on the DNA type. A method is a function with a special receiver argument.
// The receiver appears in its own argument list between the func keyword and the method name.
// Here, the Counts method has a receiver of type DNA named d.
func (d DNA) Counts() (Histogram, error) {
d = DNA(strings.ToUpper(string(d)))
h := Histogram{'A': 0, 'C': 0, 'G': 0, 'T': 0}
for _, value := range strings.Split(string(d), "") {
switch value {
case string('A'):
h['A']++
case string('C'):
h['C']++
case string('G'):
h['G']++
case string('T'):
h['T']++
default:
return h, errors.New("the string is not nucleotides")
}
}
return h, nil
}
改進版
package dna
import (
"fmt"
"strings"
)
// Histogram is a mapping from nucleotide to its count in given DNA.
// Choose a suitable data type.
type Histogram map[rune]uint
// DNA is a list of nucleotides. Choose a suitable data type.
type DNA string
// Counts generates a histogram of valid nucleotides in the given DNA.
// Returns an error if d contains an invalid nucleotide.
///
// Counts is a method on the DNA type. A method is a function with a special receiver argument.
// The receiver appears in its own argument list between the func keyword and the method name.
// Here, the Counts method has a receiver of type DNA named d.
func (d DNA) Counts() (Histogram, error) {
//d = DNA([]rune(strings.ToUpper(string(d))))
var h = Histogram{
'A': 0,
'C': 0,
'G': 0,
'T': 0,
}
m := []rune(strings.ToUpper(string(d)))
for _, nucleotide := range m {
if _, ok := h[nucleotide]; !ok {
return nil, fmt.Errorf("error")
}
h[nucleotide]++
}
return h, nil
}
您可以通過將字符串轉換為[] rune而不是使用strings.Split來將其拆分為單個字符。這也將消除大量的字符串轉換。 You can split a string into individual characters by casting it to []rune instead of using strings.Split. This will also do away with a lot of your string casts. 您可以檢查像這樣的映射中是否已經存在鍵,其中m是已經定義的映射: You can check if a key already exists in a map like this, where m is an already defined map:
在此示例中,ok是一個布爾值,指示在映射中是否存在。您可以將其使用,或者將其邏輯取反,再結合DNA序列的符文
In this example, ok is a boolean that indicates whether exists in the map. You can use this, or rather the logical negation of this, combined with the runes of the DNA sequence
安全地凋謝符文是有效的核苷酸,如果是,請在圖中增加其數量。您應該能夠在for循環中分4行執行此操作,包括錯誤檢查。
to safely tell wither a rune is a valid nucleotide, and if so, increment its count in the map. You should be able to do this in 4 lines, including error checking, inside the for loop.