fork download
  1. import math
  2.  
  3. FUEL_PER_MILE = 2.125
  4.  
  5. # Function to check if a number is an odd prime
  6. def is_odd_prime(n):
  7. if n < 2 or n % 2 == 0:
  8. return False
  9. for i in range(3, int(math.sqrt(n)) + 1, 2):
  10. if n % i == 0:
  11. return False
  12. return True
  13.  
  14. # Function to simulate the trip
  15. def simulate_trip(initial_fuel, print_output=False):
  16. fuel = initial_fuel
  17. location = 0
  18.  
  19. while fuel >= 0:
  20. if print_output:
  21. print("LOCATION: {} FUEL: {:.6f}".format(location, fuel))
  22.  
  23. if is_odd_prime(location):
  24. fuel += location # Add fuel at odd prime mile markers
  25. if print_output:
  26. print("{} FUEL ADDED AT ODD PRIME MILE MARKER".format(location))
  27.  
  28. fuel -= FUEL_PER_MILE # Consume fuel per mile
  29.  
  30. if fuel < 0:
  31. return location + (fuel / FUEL_PER_MILE) # Exact stranded location
  32.  
  33. location += 1
  34.  
  35. return float('inf') # If never stranded, return infinity
  36.  
  37. # Minimum fuel needed to never get stranded
  38. min_fuel = 6.375
  39.  
  40. # Verify if 6.375 is enough
  41. result = simulate_trip(min_fuel)
  42. if result == float('inf'):
  43. print("Minimum starting fuel: {:.6f}".format(min_fuel))
  44. else:
  45. print("ERROR: 6.375 is not enough fuel!")
  46.  
  47. # Part 2: Simulate with one drop less fuel
  48. stranded_location = simulate_trip(min_fuel - 0.0001, print_output=True)
  49. print("Final stranded location with one drop less fuel: {:.6f}".format(stranded_location))
  50.  
Success #stdin #stdout 0.02s 7264KB
stdin
Standard input is empty
stdout
ERROR: 6.375 is not enough fuel!
LOCATION: 0    FUEL: 6.374900
LOCATION: 1    FUEL: 4.249900
LOCATION: 2    FUEL: 2.124900
Final stranded location with one drop less fuel: 1.999953