gpt4 book ai didi

ruby - 使用集合合并范围 - 错误 - 堆栈级别太深 (SystemStackError)

转载 作者:太空宇宙 更新时间:2023-11-03 17:31:24 27 4
gpt4 key购买 nike

我有很多范围,如果它们重叠,我想合并在一起。我目前使用的方法是使用 Sets。

这是有效的。但是,当我尝试使用如下更大范围的相同代码时,我得到一个“堆栈级别太深(SystemStackError)”。

require 'set'

ranges = [Range.new(73, 856), Range.new(82, 1145), Range.new(116, 2914), Range.new(3203, 3241)]
set = Set.new
ranges.each { |r| set << r.to_set }
set.flatten!
sets_subsets = set.divide { |i, j| (i - j).abs == 1 } # this line causes the error

puts sets_subsets

失败的行直接取自 Ruby Set Documentation .

如果有人能提出适用于上述示例的修复或替代方案,我将不胜感激

编辑

我已经把我正在使用的完整代码放在这里:

基本上是用来根据一些特性给一个氨基酸序列加上html标签。

require 'set'

def calculate_formatting_classes(hsps, signalp)
merged_hsps = merge_ranges(hsps)
sp = format_signalp(merged_hsps, signalp)
hsp_class = (merged_hsps - sp[1]) - sp[0]
rank_format_positions(sp, hsp_class)
end

def merge_ranges(ranges)
set = Set.new
ranges.each { |r| set << r.to_set }
set.flatten
end

def format_signalp(merged_hsps, sp)
sp_class = sp - merged_hsps
sp_hsp_class = sp & merged_hsps # overlap regions between sp & merged_hsp
[sp_class, sp_hsp_class]
end

def rank_format_positions(sp, hsp_class)
results = []
results += sets_to_hash(sp[0], 'sp')
results += sets_to_hash(sp[1], 'sphsp')
results += sets_to_hash(hsp_class, 'hsp')
results.sort_by { |s| s[:pos] }
end

def sets_to_hash(set = nil, cl)
return nil if set.nil?
hashes = []
merged_set = set.divide { |i, j| (i - j).abs == 1 }
merged_set.each do |s|
hashes << { pos: s.min.to_i - 1, insert: "<span class=#{cl}>" }
hashes << { pos: s.max.to_i - 0.1, insert: '</span>' } # for ordering
end
hashes
end

working_hsp = [Range.new(7, 136), Range.new(143, 178)]
not_working_hsp = [Range.new(73, 856), Range.new(82, 1145),
Range.new(116, 2914), Range.new(3203, 3241)]

sp = Range.new(1, 20).to_set

# working
results = calculate_formatting_classes(working_hsp, sp)

# Not Working
# results = calculate_formatting_classes(not_working_hsp, sp)

puts results

最佳答案

这是一种方法:

ranges = [Range.new(73, 856), Range.new(82, 1145), 
Range.new(116, 2914), Range.new(3203, 3241)]

ranges.size.times do
ranges = ranges.sort_by(&:begin)
t = ranges.each_cons(2).to_a
t.each do |r1, r2|
if (r2.cover? r1.begin) || (r2.cover? r1.end) ||
(r1.cover? r2.begin) || (r1.cover? r2.end)
ranges << Range.new([r1.begin, r2.begin].min, [r1.end, r2.end].max)
ranges.delete(r1)
ranges.delete(r2)
t.delete [r1,r2]
end
end
end


p ranges
#=> [73..2914, 3203..3241]

关于ruby - 使用集合合并范围 - 错误 - 堆栈级别太深 (SystemStackError),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35256603/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com