useless.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. from typing import List
  2. def useless_flight(schedule: List) -> List:
  3. result = []
  4. nodes = [s for s, d, _ in schedule] + [d for s, d, _ in schedule]
  5. for i, e in enumerate(schedule):
  6. x, y, p = e
  7. graph = sorted([z for z in schedule if z != e], key=lambda x: x[2])
  8. if nodes.count(x) > 1 and nodes.count(y) > 1 and route_price(graph, x, y, [], p) < p:
  9. result.append(i)
  10. return result
  11. def route_price(graph, source, dest, visited, best=100000, price=0):
  12. if source == dest:
  13. return price
  14. for s, d, p in graph:
  15. if d == source:
  16. s, d = d, s
  17. if s == source and d not in visited and price + p < best:
  18. p_new = route_price(graph, d, dest, visited + [s], best, price + p)
  19. best = min(best, p_new)
  20. return best
  21. if __name__ == '__main__':
  22. print("Example:")
  23. print(useless_flight([['A', 'B', 50],
  24. ['B', 'C', 40],
  25. ['A', 'C', 100]]))
  26. # These "asserts" are used for self-checking and not for an auto-testing
  27. assert useless_flight([['A', 'B', 50],
  28. ['B', 'C', 40],
  29. ['A', 'C', 100]]) == [2]
  30. assert useless_flight([['A', 'B', 50],
  31. ['B', 'C', 40],
  32. ['A', 'C', 90]]) == []
  33. assert useless_flight([['A', 'B', 50],
  34. ['B', 'C', 40],
  35. ['A', 'C', 40]]) == []
  36. assert useless_flight([['A', 'C', 10],
  37. ['C', 'B', 10],
  38. ['C', 'E', 10],
  39. ['C', 'D', 10],
  40. ['B', 'E', 25],
  41. ['A', 'D', 20],
  42. ['D', 'F', 50],
  43. ['E', 'F', 90]]) == [4, 7]
  44. assert useless_flight([["A", "E", 45], ["A", "H", 85], ["A", "K", 60], ["A", "N", 20], ["B", "C", 90],
  45. ["B", "Q", 70], ["B", "X", 60], ["B", "Y", 100], ["C", "R", 55], ["C", "X", 30],
  46. ["D", "F", 10], ["D", "T", 50], ["D", "U", 75], ["D", "V", 35], ["E", "H", 55],
  47. ["E", "J", 40], ["E", "M", 35], ["F", "J", 95], ["F", "M", 10], ["G", "N", 75],
  48. ["G", "P", 75], ["G", "W", 40], ["H", "V", 15], ["I", "O", 10], ["I", "Q", 10],
  49. ["I", "S", 70], ["J", "M", 80], ["J", "V", 20], ["K", "U", 85], ["K", "V", 80],
  50. ["K", "Y", 35], ["L", "P", 15], ["L", "R", 40], ["L", "X", 50], ["N", "P", 70],
  51. ["N", "W", 30], ["O", "Q", 40], ["O", "S", 55], ["O", "U", 45], ["P", "W", 90],
  52. ["Q", "Y", 10], ["R", "X", 95], ["S", "T", 100], ["T", "U", 30], ["W", "Y", 15]]) == [7, 17, 19, 25, 26, 36, 41]