Assignment 6 AI Travelling Salesman Problem - Jupyter Notebook
The document describes a Jupyter Notebook assignment focused on solving the Travelling Salesman Problem using the nearest neighbor algorithm. It includes Python code for calculating distances between cities, generating city names, and finding a tour based on user-defined city coordinates. The output demonstrates the tour and total distance for a sample input of five cities.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
23 views1 page
Assignment 6 AI Travelling Salesman Problem - Jupyter Notebook
The document describes a Jupyter Notebook assignment focused on solving the Travelling Salesman Problem using the nearest neighbor algorithm. It includes Python code for calculating distances between cities, generating city names, and finding a tour based on user-defined city coordinates. The output demonstrates the tour and total distance for a sample input of five cities.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1
5/2/24, 11:03 AM Assignment 9 AI Travelling salesman problem - Jupyter Notebook
In [8]: import math
import random def distance(city1, city2): x1, y1 = cities[city1] x2, y2 = cities[city2] return math.sqrt((x2 - x1)**2 + (y2 - y1)**2) def generate_city_names(num_cities): return [chr(65 + i) for i in range(num_cities)] def nearest_neighbor(start_city): unvisited_cities = set(cities.keys()) unvisited_cities.remove(start_city) current_city = start_city tour = [start_city] while unvisited_cities: nearest_city = min(unvisited_cities, key=lambda city: distance(curre tour.append(nearest_city) unvisited_cities.remove(nearest_city) current_city = nearest_city tour.append(start_city) return tour # Taking input from the user n = int(input("Enter the number of cities: ")) city_names = generate_city_names(n) cities = {} print("Enter the coordinates of each city (x y):") for name in city_names: x, y = map(float, input().split()) cities[name] = (x, y) # Starting city for nearest neighbor algorithm start_city = random.choice(city_names) # Finding the tour using nearest neighbor algorithm tour = nearest_neighbor(start_city) # Displaying the result print("City Names:", city_names) print("Tour using Nearest Neighbor Algorithm:", tour) total_distance = sum(distance(tour[i], tour[i+1]) for i in range(len(tour)-1 print("Total Distance:", total_distance)
Enter the number of cities: 5
Enter the coordinates of each city (x y): 2 5 4 8 5 2 7 6 54 8 City Names: ['A', 'B', 'C', 'D', 'E'] Tour using Nearest Neighbor Algorithm: ['C', 'A', 'B', 'D', 'E', 'C'] Total Distance: 107.8622573721935
localhost:8888/notebooks/Assignment 9 AI Travelling salesman problem.ipynb 1/2