fork download
  1. def calculate_total_distance_from_input(input_data):
  2. # Parse the input into two lists
  3. left_list = []
  4. right_list = []
  5.  
  6. for line in input_data.strip().split("\n"):
  7. left, right = map(int, line.split())
  8. left_list.append(left)
  9. right_list.append(right)
  10.  
  11. # Sort both lists
  12. left_sorted = sorted(left_list)
  13. right_sorted = sorted(right_list)
  14.  
  15. # Calculate the total distance
  16. total_distance = 0
  17. for left, right in zip(left_sorted, right_sorted):
  18. total_distance += abs(left - right)
  19.  
  20. return total_distance
  21.  
  22.  
  23. # Example Input
  24. input_data = """
  25. 76309 75213
  26. 79731 28444
  27. 29583 71339
  28. 60992 99148
  29. 34680 74530
  30. 45691 82519
  31. 55358 22047
  32. 95523 45384
  33. 37661 82208
  34. 33464 91461
  35. 26897 96393
  36. 76556 76554
  37. 82316 98880
  38. 92079 23082
  39. 55539 10033
  40. 65931 66060
  41. 98880 60464
  42. 19348 41458
  43. 72003 84074
  44. 78401 78856
  45. 53187 72003
  46. """
  47.  
  48. # Calculate and print the result
  49. result = calculate_total_distance_from_input(input_data)
  50. print("Total Distance:", result)
Success #stdin #stdout 0.03s 9864KB
stdin
Standard input is empty
stdout
Total Distance: 161393