Advertisement
Guest User

Untitled

a guest
Jul 17th, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. class Position:
  4. def __init__(self, file, offset):
  5. '''A position has both a file and offset'''
  6. self.file = file
  7. self.offset = offset
  8.  
  9. def __lt__(self, other):
  10. '''Positions are ordered first by file then by offset.'''
  11. if self.file < other.file:
  12. return True
  13. elif self.file == other.file:
  14. return self.offset < other.offset
  15. else:
  16. return False
  17.  
  18. def __eq__(self, other):
  19. '''Positions are equal if the file and offset are the same.'''
  20. return self.file == other.file and self.offset == other.offset
  21.  
  22. def __str__(self):
  23. '''Pretty print for Position.'''
  24. return f'(file={self.file}, offset={self.offset})'
  25.  
  26.  
  27. def binary_search(data, target):
  28. '''Returns the index of ``target`` within the sorted list, ``data``.
  29.  
  30. If ``target`` is not in ``data``, return the index at which it can be
  31. inserted to maintain sorted order.
  32. '''
  33. lo = 0
  34. hi = len(data)
  35.  
  36. while 1 < hi - lo:
  37. mid = (hi + lo) // 2
  38. if target < data[mid]:
  39. hi = mid
  40. elif data[mid] < target:
  41. lo = mid
  42. else:
  43. assert data[mid] == target
  44. return mid
  45.  
  46. return lo + 1
  47.  
  48.  
  49. if __name__ == '__main__':
  50. import random
  51.  
  52. chapters = [
  53. Position(file=0, offset=0),
  54. Position(file=1, offset=85),
  55. Position(file=2, offset=1),
  56. Position(file=5, offset=33),
  57. Position(file=7, offset=50),
  58. Position(file=7, offset=51),
  59. Position(file=9, offset=0),
  60. ]
  61.  
  62. for _ in range(25):
  63. file = random.randrange(10)
  64. offset = random.randrange(100)
  65. pos = Position(file, offset)
  66. index = binary_search(chapters, pos)
  67. print(f'Position {pos} is in chapter {index - 1}')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement