Using a greedy algorithm

If we use a greedy algorithm to solve the TSP, then, at each step, we can choose a city that seems reasonable, instead of finding a city to visit that will result in the best overall path. So, whenever we need to select a city, we just select the nearest city without bothering to verify that this choice will result in the globally optimal path.

The approach of the greedy algorithm is simple:

  1. Start from any city.
  2. At each step, keep building the tour by moving to the next city where the nearest neighborhood has not been visited before.
  3. Repeat step 2.

Let's define a function named greedy_algorithm that can implement this logic:

def greedy_algorithm(cities, start=None):
C = start or first(cities)
tour = [C]
unvisited = set(cities - {C})
while unvisited:
C = nearest_neighbor(C, unvisited)
tour.append(C)
unvisited.remove(C)
return tour

def first(collection): return next(iter(collection))

def nearest_neighbor(A, cities):
return min(cities, key=lambda C: distance_points(C, A))

Now, let's use greedy_algorithm to create a tour for 2,000 cities:

Note that it took only 0.514 seconds to generate the tour for 2,000 cities. If we had used the brute-force method, it would have generated (2000-1)! permutations, which is almost infinity.

Note that the greedy algorithm is based on heuristics and there is no proof that the solution will be optimal.

Now, let's look at the design of the PageRank algorithm.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.184.6