fork download
  1. def query_sum(seq, target):
  2. def bsearch(l, r):
  3. if r >= l:
  4. mid = l + (r - l) // 2
  5. s = sum(seq[mid:mid + 2])
  6. if s == target:
  7. return mid
  8. elif s > target:
  9. return bsearch(l, mid - 1)
  10. else:
  11. return bsearch(mid + 1, r)
  12. else:
  13. return -1
  14. i = bsearch(0, len(seq) - 1)
  15. if i < 0:
  16. return False
  17. print("Yes sum exist with pair {} {}".format(*seq[i:i + 2]))
  18. return True
  19.  
  20. x = [1, 2, 3, 4, 5]
  21. y = [1, 2, 4, 8, 16]
  22.  
  23. query_sum(x, 7)
  24. query_sum(y, 3)
Success #stdin #stdout 0.02s 9108KB
stdin
Standard input is empty
stdout
Yes sum exist with pair 3 4
Yes sum exist with pair 1 2