|
| 1 | +""" Breadth-first search |
| 2 | +
|
| 3 | +This ignores the distance between the city data, and just cares about number of hops. |
| 4 | +
|
| 5 | +This implementation is admittedly tightly-coupled to my particular city_data data set |
| 6 | +(to add clarity in understanding by making it tied to concrete data). |
| 7 | +
|
| 8 | +The city_data is a list of 28 large cities in the United States, with some considered |
| 9 | +neighbors of the others. This would be the case in, say, a bus system which only |
| 10 | +travels between major cities. Using the shortest path on this data outputs |
| 11 | +the best path through these major cities. |
| 12 | +
|
| 13 | +The format of city_data is like this: |
| 14 | +
|
| 15 | +{ "Milwaukee, WI": {"Minneapolis, MN": 542093, "Chicago, IL": 148198}, |
| 16 | + "Minneapolis, MN": {"Seattle, WA": 2665735, "Milwaukee, WI": 541660}, ... } |
| 17 | +
|
| 18 | +So the neighbors of a city node can be found like this: list(city_data["Milwaukee, WI"].keys()) |
| 19 | +
|
| 20 | +""" |
| 21 | + |
| 22 | +import json |
| 23 | +import sys |
| 24 | + |
| 25 | + |
| 26 | +def unroll_shortest_path(current, optimal_parent_map, path=()): |
| 27 | + if current is None: # Reached the start node |
| 28 | + return path |
| 29 | + else: |
| 30 | + return unroll_shortest_path(optimal_parent_map[current], optimal_parent_map, (current,) + path) |
| 31 | + |
| 32 | + |
| 33 | +def get_city_data(): |
| 34 | + city_data = None |
| 35 | + with open("city_data.json","r") as f: |
| 36 | + city_data = json.loads(f.read()) |
| 37 | + return city_data |
| 38 | + |
| 39 | + |
| 40 | +def depth_first_search(from_city, to_city, city_data): |
| 41 | + visited = set() |
| 42 | + |
| 43 | + def _depth_first_search(from_city, to_city, city_data, path=()): |
| 44 | + print("Checking: {}".format(from_city)) |
| 45 | + if from_city == to_city: |
| 46 | + return path |
| 47 | + elif len(visited) == len(city_data): |
| 48 | + print("HIT") |
| 49 | + return None |
| 50 | + else: |
| 51 | + neighbors = list(city_data[from_city].keys()) |
| 52 | + visited.add(from_city) |
| 53 | + for n in neighbors: |
| 54 | + if n not in visited: |
| 55 | + result = _depth_first_search(n, to_city, city_data, path+(n,)) |
| 56 | + if result is not None: |
| 57 | + return result |
| 58 | + |
| 59 | + return _depth_first_search(from_city, to_city, city_data) |
| 60 | + |
| 61 | + |
| 62 | +if __name__ == '__main__': |
| 63 | + city_data = get_city_data() |
| 64 | + try: |
| 65 | + city_from = sys.argv[1] |
| 66 | + city_to = sys.argv[2] |
| 67 | + except IndexError: |
| 68 | + print("Usage:", sys.argv[0], "\"from city\" \"to city>\"") |
| 69 | + print("City choices:") |
| 70 | + for city in city_data: |
| 71 | + print(" -", city) |
| 72 | + sys.exit(1) |
| 73 | + |
| 74 | + print(depth_first_search(city_from, city_to, city_data)) |
| 75 | + |
0 commit comments