如何在序列中找到多个"图案"的第一个索引?

Sys*_*tem 3 julia

我正在学习Julia,但是在R之外的编程经验相对较少.我直接从rosalind.info中解决这个问题,你可以在这里找到它,如果你想要更多的细节.

我给了两个字符串:一个主题和一个序列,其中主题是序列的子串,我的任务是查找子串的起始位置的索引,但是在序列中找到很多次.

例如:

顺序:"GATATATGCATATACTT"

主题:"ATAT"

发现ATAT三次,一次从索引2开始,一次在索引4,一次在索引10.这假设基于1的索引.所以最终的输出是:2 4 10

这是我到目前为止所拥有的:

f = open("motifs.txt")
stream = readlines(f)

sequence = chomp(stream[1])
motif = chomp(stream[2])

println("Sequence: $sequence")
println("Motif: $motif")

result = searchindex(sequence, motif)
println("$result")

close(f)
Run Code Online (Sandbox Code Playgroud)

我的主要问题似乎是没有searchindexall选项.当前的脚本给了我第一次遇到主题的第一个索引(索引2),我尝试了各种for循环但没有取得太大的成功,所以我希望有人可以给我一些见解就此而言.

nic*_*y12 6

这是一个while循环的解决方案:

sequence = "GATATATGCATATACTT"
motif = "ATAT"

function find_indices(sequence, motif)
    # initalise empty array of integers
    found_indices = Array{Int, 1}()

    # set initial values for search helpers
    start_at = 1

    while true
      # search string for occurrence of motif
      result = searchindex(sequence, motif, start_at)

      # if motif not found, terminate while loop
      result == 0 && break

      # add new index to results
      push!(found_indices, result-1+start_at)
      start_at += result + 1
   end

   return found_indices
end
Run Code Online (Sandbox Code Playgroud)

这给了你想要的东西:

>find_indices(sequence, motif)
2
4
10
Run Code Online (Sandbox Code Playgroud)

  • @System,是的.这正是它的作用.很高兴它对你有效. (2认同)