Introduction to Programming using Python 1st Edition

Published by Pearson
ISBN 10: 0132747189
ISBN 13: 978-0-13274-718-9

Chapter 11 - Multidimensional Lists - Programming Exercises - Page 393: 11.35

Answer

import math n=int(input("Enter the number of cities:")) a=list(map(float,input("Enter the coordinates of the cities:").split())) cities=[(a[2*i-2], a[2*i-1]) for i in range(1,n+1)] centralCityIndex=0 minTotalDistance=99999999999999999999 # Initialize with a large value for i in range(n): distance=0 for j in range(n): if i!=j: distance+=math.sqrt((cities[i][0]-cities[j][0])**2+(cities[i][1]-cities[j][1])**2) if distance

Work Step by Step

First we take the input. Then we create a variable to store the index of central city and another variable to store the minimum total distance from the cities, initially this is set to very high value. Then we check for all cities the distance with every other city and select the one with minimum total distance using the two nested for loops.
Update this answer!

You can help us out by revising, improving and updating this answer.

Update this answer

After you claim an answer you’ll have 24 hours to send in a draft. An editor will review the submission and either publish your submission or provide feedback.