你怎么找到多个主题的第一个索引'顺序?

时间:2016-04-05 13:36:25

标签: julia

我正在学习朱莉娅,但在R之外的编程经验相对较少。我直接从rosalind.info处理这个问题,你可以找到它here如果你这样做了比较详细一点。

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

例如:

序列:" 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)

我的主要问题似乎是没有searchindexall选项。当前的脚本给了我第一次遇到主题的第一个索引(索引2),我已经尝试了各种for循环,并没有取得很大成功,所以我希望这样有人可以给我一些见解。

2 个答案:

答案 0 :(得分: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

这给出了你想要的东西:

>find_indices(sequence, motif)
2
4
10

答案 1 :(得分:1)

如果表现不那么重要,正则表达式可能是一个不错的选择。

julia> map(x->x.offset, eachmatch(r"ATAT", "GATATATGCATATACTT", true))
3-element Array{Any,1}:
  2
  4
 10

PS。 eachmatch的第三个论点意味着"重叠",不要忘记将其设置为真。

如果需要更好的性能,也许您应该花一些时间来实现像KMP这样的算法。

相关问题