Skip to content

Commit 8b9cc91

Browse files
authored
Merge pull request sumanth-0#703 from DevNexis/issue-617-road-trip-planner
Fix sumanth-0#617: Add Road Trip Route Planner
2 parents 713e108 + 14d0319 commit 8b9cc91

File tree

2 files changed

+183
-0
lines changed

2 files changed

+183
-0
lines changed
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
# Road Trip Route Planner 🚗🗺️
2+
3+
A simple Python script for planning optimal road trip routes between cities with basic path optimization.
4+
5+
## Features
6+
7+
- **Static City Map**: Pre-configured network of major US cities
8+
- **Dual Optimization Modes**:
9+
- Shortest distance (km)
10+
- Fastest time (hours)
11+
- **Dijkstra's Algorithm**: Efficient pathfinding for optimal routes
12+
- **Interactive CLI**: User-friendly command-line interface
13+
- **Visual Route Display**: Clear step-by-step route visualization
14+
15+
## Usage
16+
17+
### Run the Script
18+
19+
```bash
20+
python road_trip_planner.py
21+
```
22+
23+
### Example Session
24+
25+
```
26+
🚗 ROAD TRIP ROUTE PLANNER 🗺️
27+
Available cities:
28+
Atlanta, Boston, Charlotte
29+
Chicago, Cincinnati, Cleveland
30+
...
31+
32+
Enter starting city: New York
33+
Enter destination city: Chicago
34+
35+
Optimization options:
36+
1. Shortest distance
37+
2. Fastest time
38+
Choose option (1/2): 1
39+
40+
============================================================
41+
Route (DISTANCE optimized):
42+
1. New York
43+
44+
2. Philadelphia
45+
46+
3. Pittsburgh
47+
48+
4. Cleveland
49+
50+
5. Detroit
51+
52+
6. Chicago
53+
54+
Total distance: 985.0 km
55+
============================================================
56+
```
57+
58+
## How It Works
59+
60+
1. **City Network**: The script uses a static graph where cities are nodes and routes are weighted edges
61+
2. **Dijkstra's Algorithm**: Finds the optimal path based on selected criteria (distance or time)
62+
3. **Priority Queue**: Uses heapq for efficient path exploration
63+
4. **Path Reconstruction**: Tracks the complete route from start to destination
64+
65+
## Requirements
66+
67+
- Python 3.6 or higher
68+
- No external dependencies (uses only Python standard library)
69+
70+
## Limitations
71+
72+
- Static map with pre-defined cities (21 major US cities)
73+
- Simplified distance and time calculations
74+
- No real-time traffic data
75+
- Limited to connected cities in the network
76+
77+
## Future Enhancements
78+
79+
- Add more cities and routes
80+
- Support for waypoints/multiple stops
81+
- Export routes to file
82+
- Integration with mapping APIs
83+
- Fuel cost calculations
84+
85+
## Author
86+
87+
Created for issue #617 - 100 Lines of Python Code Project
88+
89+
## License
90+
91+
Open source - feel free to modify and enhance!
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
#!/usr/bin/env python3
2+
"""Road Trip Route Planner - Plan optimal routes between cities"""
3+
4+
import heapq
5+
from typing import Dict, List, Tuple, Optional
6+
7+
# Static map of cities with distances (km) and travel times (hours)
8+
CITY_MAP = {
9+
'New York': [('Boston', 215, 3.5), ('Philadelphia', 95, 1.8), ('Washington', 225, 3.8)],
10+
'Boston': [('New York', 215, 3.5), ('Portland', 105, 2.0)],
11+
'Philadelphia': [('New York', 95, 1.8), ('Washington', 140, 2.3), ('Pittsburgh', 305, 5.0)],
12+
'Washington': [('New York', 225, 3.8), ('Philadelphia', 140, 2.3), ('Richmond', 110, 1.8)],
13+
'Pittsburgh': [('Philadelphia', 305, 5.0), ('Cleveland', 135, 2.2), ('Columbus', 185, 3.0)],
14+
'Cleveland': [('Pittsburgh', 135, 2.2), ('Detroit', 170, 2.8), ('Columbus', 145, 2.4)],
15+
'Detroit': [('Cleveland', 170, 2.8), ('Chicago', 280, 4.5)],
16+
'Chicago': [('Detroit', 280, 4.5), ('Milwaukee', 90, 1.5), ('St Louis', 300, 4.8)],
17+
'Columbus': [('Pittsburgh', 185, 3.0), ('Cleveland', 145, 2.4), ('Cincinnati', 110, 1.8)],
18+
'Cincinnati': [('Columbus', 110, 1.8), ('Louisville', 100, 1.6), ('Indianapolis', 110, 1.8)],
19+
'Indianapolis': [('Cincinnati', 110, 1.8), ('Chicago', 185, 3.0), ('Louisville', 115, 1.9)],
20+
'Louisville': [('Cincinnati', 100, 1.6), ('Indianapolis', 115, 1.9), ('Nashville', 175, 2.8)],
21+
'Nashville': [('Louisville', 175, 2.8), ('Memphis', 210, 3.3), ('Atlanta', 250, 4.0)],
22+
'Atlanta': [('Nashville', 250, 4.0), ('Charlotte', 245, 3.9), ('Jacksonville', 345, 5.5)],
23+
'Charlotte': [('Atlanta', 245, 3.9), ('Richmond', 300, 4.8)],
24+
'Richmond': [('Washington', 110, 1.8), ('Charlotte', 300, 4.8)],
25+
'Milwaukee': [('Chicago', 90, 1.5)],
26+
'St Louis': [('Chicago', 300, 4.8), ('Memphis', 285, 4.5)],
27+
'Memphis': [('St Louis', 285, 4.5), ('Nashville', 210, 3.3)],
28+
'Portland': [('Boston', 105, 2.0)],
29+
'Jacksonville': [('Atlanta', 345, 5.5)]
30+
}
31+
32+
def dijkstra(start: str, end: str, optimize: str = 'distance') -> Optional[Tuple[List[str], float]]:
33+
"""Find optimal route using Dijkstra's algorithm"""
34+
if start not in CITY_MAP or end not in CITY_MAP:
35+
return None
36+
37+
idx = 1 if optimize == 'distance' else 2
38+
pq = [(0, start, [start])]
39+
visited = set()
40+
41+
while pq:
42+
cost, city, path = heapq.heappop(pq)
43+
if city in visited:
44+
continue
45+
if city == end:
46+
return path, cost
47+
visited.add(city)
48+
for neighbor, dist, time in CITY_MAP.get(city, []):
49+
if neighbor not in visited:
50+
heapq.heappush(pq, (cost + (dist if idx == 1 else time), neighbor, path + [neighbor]))
51+
return None
52+
53+
def display_route(route: List[str], cost: float, optimize: str):
54+
"""Display route information"""
55+
print(f"\n{'='*60}")
56+
print(f"Route ({optimize.upper()} optimized):")
57+
for i, city in enumerate(route):
58+
print(f" {i+1}. {city}")
59+
if i < len(route) - 1:
60+
print(" ↓")
61+
unit = 'km' if optimize == 'distance' else 'hours'
62+
print(f"\nTotal {optimize}: {cost:.1f} {unit}")
63+
print(f"{'='*60}")
64+
65+
def main():
66+
print("\n🚗 ROAD TRIP ROUTE PLANNER 🗺️")
67+
print("Available cities:")
68+
cities = sorted(CITY_MAP.keys())
69+
for i in range(0, len(cities), 3):
70+
print(" " + ", ".join(cities[i:i+3]))
71+
72+
try:
73+
start = input("\nEnter starting city: ").strip()
74+
end = input("Enter destination city: ").strip()
75+
print("\nOptimization options:")
76+
print(" 1. Shortest distance")
77+
print(" 2. Fastest time")
78+
choice = input("Choose option (1/2): ").strip()
79+
80+
optimize = 'distance' if choice == '1' else 'time'
81+
result = dijkstra(start, end, optimize)
82+
83+
if result:
84+
route, cost = result
85+
display_route(route, cost, optimize)
86+
else:
87+
print(f"\n❌ No route found between {start} and {end}")
88+
except KeyboardInterrupt:
89+
print("\n\nExiting...")
90+
91+
if __name__ == "__main__":
92+
main()

0 commit comments

Comments
 (0)