Advertisement
Guest User

Untitled

a guest
Jun 22nd, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. from operator import itemgetter
  2.  
  3.  
  4. def area(items):
  5. return len(items) * sum(i[1] - i[0] for i in items)
  6.  
  7.  
  8. def mutually_exclusive_list_list_intervals(data):
  9. """
  10. Data is list of lists of intervals. We'd like to keep the most number of
  11. high level lists such that none of the intervals intersect.
  12.  
  13. This is an approximate, greedy, solution that guarentees no intersection
  14. but may not be the optimal solution. It runs at O(n logn) so that's not
  15. bad.
  16. """
  17. data_expanded = [(*d, area(items), i)
  18. for i, items in enumerate(data)
  19. for d in items]
  20. data_expanded.sort(key=lambda item: item[0])
  21. to_remove = set()
  22. i = 0
  23. de = data_expanded
  24. while i < len(de) - 1:
  25. # make sure current element is not marked for deletion
  26. if de[i][4] not in to_remove:
  27. # now we make sure the next item to compare against isn't marked
  28. # for deletion
  29. j = i + 1
  30. try:
  31. while de[j][4] in to_remove:
  32. j += 1
  33. except IndexError:
  34. break
  35. # check if this endpoint is after the next items start
  36. if de[i][1] > de[j][0]:
  37. this_area = de[i][3]
  38. next_area = de[j][3]
  39. # pick the item with the least "area" in terms of the higher
  40. # order list of intervals. This is a heuristic to remove long
  41. # lists of small intervals. We want those out because they have
  42. # a higher probability of intersecting with many other lists of
  43. # intervals.
  44. if this_area < next_area:
  45. to_remove.add(de[j][4])
  46. else:
  47. to_remove.add(de[i][4])
  48. i += 1
  49. return [d for i, d in enumerate(data) if i not in to_remove]
  50.  
  51.  
  52. data = [
  53. [(1, 5, 'a')],
  54. [(6, 9, 'b')],
  55. [(8, 20, 'c')],
  56. [(7, 8, 'a'), (9, 10, 'c')],
  57. ]
  58.  
  59. print(data)
  60. print(mutually_exclusive_list_list_intervals(data))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement