xcode - swift 2 : Function counting occurrence in string not working

标签 xcode swift count swift-playground

我正在尝试学习 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 并且 lengthFloat,您必须在某处进行一些转换。或者改变一些类型。

考虑到这一点并进行了一些改进,我得到了这个:

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/

相关文章:

function - 快速访问函数中定义的函数

ios - 试图将数组传递给 swift 函数

mysql - 一个查询中包含多个计数

python - 为什么 "test".count ('' ) 返回 5?

对穿过路径的代理进行计数

ios - 项目从 git 编译但在 Xcode 6 中不是新的

c - 在 Xcode 中为 C 程序寻址

c - xCode 产生 "Undefined symbols for architecture x86_64"错误,而 gcc 编译没有错误

ios - 在 Swift 4 中从字符串对象创建 CFData 对象

c++ - swift 3 中是否有等效的 c++ shared_ptr?