Data Structures vs Algorithms: Three Python Examples from a Railway System
A sorted list helps us find a train, a linked list models changing bookings, and a graph connects stations. Run all three Python programs below.
Core idea: A data structure organizes information; an algorithm specifies steps to process it. The best pairing depends on the operations you need.
Sorted array + binary search
Find a train quickly
The sorted Python list is the data structure: it holds train names in alphabetical order. Binary search is the algorithm: it compares the target with the middle item and discards half the remaining list at each step.
Try it yourself
- Run the editor with
Shatabdi Expressin standard input. The program returns index3. - Try
Rajdhani Expressor a name absent from the list. - Binary search needs sorted data. Its search time is O(log n); maintaining the sorted array after insertions can cost O(n).
Linked list + booking operations
Add and cancel records
A linked list stores each booking in a node that points to the next one. The code adds a new booking at the head, traverses the list, and unlinks a matching booking when cancelled.
Try it yourself
- Run the editor. It books Asha, Ravi and Meena, then cancels Ravi.
- Adding at the head takes O(1). Finding Ravi by name requires a scan, so cancellation takes O(n).
- This is a teaching model. A real ticketing system would use unique booking IDs and persistent storage.
Graph + shortest path
Choose a route between stations
The graph represents stations as vertices and railway connections as weighted edges. Dijkstra’s algorithm explores routes in order of distance using a priority queue, then returns the shortest path for nonnegative weights.
Try it yourself
- Run with
Varanasion the first input line andLucknowon the second. - The sample returns Varanasi → Prayagraj → Lucknow, 330 km.
- The distances are illustrative, not official railway distances or train schedules.
Compare the three examples
| Railway task | Data structure | Algorithm or operation | Key point |
|---|---|---|---|
| Find a train | Sorted list (array) | Binary search | Fast search when the list is sorted |
| Change bookings | Linked list | Add, traverse, unlink | Head insertion is fast; name lookup still scans |
| Find a route | Weighted graph | Dijkstra’s shortest path | Connections and distances shape the result |
Practice: Add one train, cancel a different passenger, and change one route distance. Predict each result before running the code.
Which data structure would you choose for a live train timetable, and why? Share your reasoning in the comments.
0 Comments
Please comment