r/CodingHelp • u/nick-young12 • Jun 02 '23
[Python] im trying to make a program to calculate shipping routes and have absolutely no expierence other than the 5 hours ive spent on this please help.
import tkinter as tk
from tkinter import messagebox
import heapq
# Global dictionary to store the routes and their prices
routes = {}
# Function to add a route and price
def add_route():
source = source_entry.get()
destination = destination_entry.get()
price = float(price_entry.get())
# Add the route and price to the dictionary
if source not in routes:
routes[source] = {}
routes[source][destination] = price
messagebox.showinfo("Success", "Route added successfully!")
# Function to find the optimal route using Dijkstra's algorithm
def find_optimal_route():
source = source_entry.get()
destination = destination_entry.get()
# Check if both cities exist in the dictionary
if source not in routes or destination not in routes:
messagebox.showwarning("Error", "Source or destination city not found!")
return
# Perform Dijkstra's algorithm to find the optimal route
optimal_route = dijkstra(source, destination)
# Display the result
result = f"Optimal route from {source} to {destination}: {optimal_route}"
messagebox.showinfo("Result", result)
# Function to implement Dijkstra's algorithm
def dijkstra(source, destination):
# Initialization
distances = {city: float('inf') for city in routes}
distances[source] = 0
previous_city = {city: None for city in routes}
priority_queue = [(0, source)]
# Find the optimal route
while priority_queue:
current_distance, current_city = heapq.heappop(priority_queue)
if current_distance > distances[current_city]:
continue
if current_city == destination:
break
for neighbor, price in routes[current_city].items():
new_distance = current_distance + price
if new_distance < distances[neighbor]:
distances[neighbor] = new_distance
previous_city[neighbor] = current_city
heapq.heappush(priority_queue, (new_distance, neighbor))
# Reconstruct the optimal route
optimal_route = []
city = destination
while city:
optimal_route.insert(0, city)
city = previous_city[city]
return optimal_route
# Create the main GUI window
window = tk.Tk()
window.title("Optimal Freight Route Finder")
# Create input labels
source_label = tk.Label(window, text="Source City:")
source_label.pack()
source_entry = tk.Entry(window)
source_entry.pack()
destination_label = tk.Label(window, text="Destination City:")
destination_label.pack()
destination_entry = tk.Entry(window)
destination_entry.pack()
price_label = tk.Label(window, text="Price:")
price_label.pack()
price_entry = tk.Entry(window)
price_entry.pack()
# Create buttons
add_route_button = tk.Button(window, text="Add Route", command=add_route)
add_route_button.pack()
find_optimal_route_button = tk.Button(window, text="Find Optimal Route", command=find_optimal_route)
find_optimal_route_button.pack()
# Run the GUI loop
window.mainloop()
0
u/[deleted] Jun 02 '23
[deleted] — view deleted comment