Using Python, write a program that accepts two subject IDs and returns the most
ID: 3763390 • Letter: U
Question
Using Python, write a program that accepts two subject IDs and returns the most recent common ancestor of the two indiciduals if there is any, otherwise return None. Use the following table as a sample (0 means missing parents, everyone with both missing parents are founders of the pedigree, and founders are not related)
Thanks!
Individual ID Paternal ID Maternal ID 0 0 2 2 0 0 101 0 0 102 0 0 103 0 0 104 0 0 105 0 0 106 0 0 301 2 1 302 101 301 303 101 301 304 101 301 305 101 301 306 101 301 307 101 301 308 2 1 309 102 308 310 102 308 311 102 308 312 102 308 313 102 308 314 102 308 315 2 1 316 103 315 317 103 315 318 103 315 319 103 315 320 103 315 321 103 315 322 105 321 323 106 302Explanation / Answer
def bin_search(search, subject)
discarded_left = 0
while subject.any?
mid = subject.length / 2
comparison = search <=> subject[mid]
return comparison.zero? ? discarded_left : nil if subject.one?
case comparison
when -1
subject = subject[0...mid]
when 1
subject = subject[mid...subject.length]
discarded_left += mid
else
return discarded_left + mid
end
end
end
$passes = 0
$fails = 0
def assert_bin_search(expect, search, subject)
found = bin_search(search, subject);
pass = found === expect
puts "FAIL: search:%d expect:%s got:%s in [%s]" %
[search, expect.inspect, found.inspect, subject.join(',')] unless pass
pass ? $passes += 1 : $fails += 1
end
subject = [4, 5, 7, 11, 19, 29, 42, 69, 129, 182, 189, 190, 250]
# test each value
subject.each_with_index do |value, index|
assert_bin_search(index, value, subject)
end
# test out-of-bounds and gaps
((0..500).to_a - subject).each do |value|
assert_bin_search(nil, value, subject)
end
# test empty subject
assert_bin_search(nil, 1, [])
puts "Passes: #{$passes} Fails: #{$fails}"
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.