我正在尝试学习 Swift 2
和计算输入字符串中 G 和 C 的频率。
我在字符串的 for 循环中没有得到任何计数。 Xcode 建议我使用 let
而不是 var
因为 gc_count
因为它没有更新(不应该是这种情况!)。
我的 return
语句也出现了这个错误:
Binary operator '/' cannot be applied to operands of type 'Double' and 'Float'
已尝试 Swift 2 - Search in string and sum the numbers
func GC(input_seq: String) -> Float {
let SEQ = input_seq.uppercaseString
var gc_count = 0.0
for nt in SEQ.characters {
print(nt)
if (nt == "G") {
var gc_count = gc_count + 1
}
if (nt == "C") {
var gc_count = gc_count + 1
}
}
var length: Float = Float(SEQ.characters.count)
return gc_count/length
}
let query_seq = "ATGGGGCTTTTGA"
GC(query_seq)
如果我用 Python 来做,我会简单地:
def GC(input_seq):
SEQ = input_seq.upper()
gc_count = 0.0
for nt in SEQ:
if (nt == "G") or (nt == "C"):
gc_count += 1
return gc_count/len(SEQ)
最佳答案
尝试替换
if (nt == "G") {
var gc_count = gc_count + 1
}
if (nt == "C") {
var gc_count = gc_count + 1
}
与
if (nt == "G") {
gc_count = gc_count + 1
}
if (nt == "C") {
gc_count = gc_count + 1
}
如果在 if
主体中写入 var gc_count
,则会创建一个新的局部变量 gc_count
,它会隐藏 gc_count
来自外部作用域。
此外,使用 let
作为长度,因为您不会更改它。
并且由于 gc_count 是 Double
,并且您的函数返回 Float
并且 length
是 Float
,您必须在某处进行一些转换。或者改变一些类型。
考虑到这一点并进行了一些改进,我得到了这个:
func GC(input_seq: String) -> Float {
let SEQ = input_seq.uppercaseString
var gc_count = 0
for nt in SEQ.characters {
print(nt)
if nt == "G" || nt == "C" {
gc_count = gc_count + 1
}
}
let length = Float(SEQ.characters.count)
return Float(gc_count) / length
}
关于xcode - swift 2 : Function counting occurrence in string not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32682128/