bisect.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. """Bisection algorithms."""
  2. def insort_right(a, x, lo=0, hi=None):
  3. """Insert item x in list a, and keep it sorted assuming a is sorted.
  4. If x is already in a, insert it to the right of the rightmost x.
  5. Optional args lo (default 0) and hi (default len(a)) bound the
  6. slice of a to be searched.
  7. """
  8. lo = bisect_right(a, x, lo, hi)
  9. a.insert(lo, x)
  10. def bisect_right(a, x, lo=0, hi=None):
  11. """Return the index where to insert item x in list a, assuming a is sorted.
  12. The return value i is such that all e in a[:i] have e <= x, and all e in
  13. a[i:] have e > x. So if x already appears in the list, a.insert(x) will
  14. insert just after the rightmost x already there.
  15. Optional args lo (default 0) and hi (default len(a)) bound the
  16. slice of a to be searched.
  17. """
  18. if lo < 0:
  19. raise ValueError('lo must be non-negative')
  20. if hi is None:
  21. hi = len(a)
  22. while lo < hi:
  23. mid = (lo+hi)//2
  24. if x < a[mid]: hi = mid
  25. else: lo = mid+1
  26. return lo
  27. def insort_left(a, x, lo=0, hi=None):
  28. """Insert item x in list a, and keep it sorted assuming a is sorted.
  29. If x is already in a, insert it to the left of the leftmost x.
  30. Optional args lo (default 0) and hi (default len(a)) bound the
  31. slice of a to be searched.
  32. """
  33. lo = bisect_left(a, x, lo, hi)
  34. a.insert(lo, x)
  35. def bisect_left(a, x, lo=0, hi=None):
  36. """Return the index where to insert item x in list a, assuming a is sorted.
  37. The return value i is such that all e in a[:i] have e < x, and all e in
  38. a[i:] have e >= x. So if x already appears in the list, a.insert(x) will
  39. insert just before the leftmost x already there.
  40. Optional args lo (default 0) and hi (default len(a)) bound the
  41. slice of a to be searched.
  42. """
  43. if lo < 0:
  44. raise ValueError('lo must be non-negative')
  45. if hi is None:
  46. hi = len(a)
  47. while lo < hi:
  48. mid = (lo+hi)//2
  49. if a[mid] < x: lo = mid+1
  50. else: hi = mid
  51. return lo
  52. # Overwrite above definitions with a fast C implementation
  53. try:
  54. from _bisect import *
  55. except ImportError:
  56. pass
  57. # Create aliases
  58. bisect = bisect_right
  59. insort = insort_right