Answer to Question #273803 in Python for Aaruhi

Question #273803

Find latitude and longitude of first 20 countries with a population greater than or equal to the population limit given below. Use the country details from this dataset.

Your task is to find the sum of the length of all lines (in kms) that can be drawn between co-ordinates of these countries.

  • Assume radius of earth: 6371 km
  • Round length of each line and final result to 2 decimal points
  • If co-ordinates are missing for any country use 0.000 N 0.000 E

Population limit: 300



1
Expert's answer
2021-11-30T18:39:53-0500


SOLUTION CODE


#let us import libraries
from math import radians, cos, sin, asin, sqrt, atan2

import json

def distance_function(lat1, lat2, lon1, lon2):
    lon1 = radians(lon1)
    lon2 = radians(lon2)
    lat1 = radians(lat1)
    lat2 = radians(lat2)
    dlon = lon2 - lon1
    dlat = lat2 - lat1

    a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2

    c = 2 * asin(sqrt(a))
    r = 6371
    return (c * r)

limitval = int(input('Limit - '))
requiredlist = []
f = open('countriesV2.json', )
totalsum = 0
# returns JSON object as
# a dictionary
data = json.load(f)
count = 0

# Iterating through the json
for i in range(len(data)):
    x = data[i]['population']

    if (x >= limitval):
        # print(i,x,data[i]['latlng'])
        requiredlist.append([i, x, data[i]['latlng']])

requiredlist = sorted(requiredlist, key=lambda x: x[1])
requiredlist.reverse()

print(requiredlist)
for i in range(0, 20):
    # print(data[requiredlist[i][0]]['name'])
    print(requiredlist[i][0])
    lat1 = requiredlist[i][2][0]
    lon1 = requiredlist[i][2][1]
    for j in range(i + 1, 20):
        if (requiredlist[i][0] != requiredlist[j][0]):
            lat2 = requiredlist[j][2][0]
            lon2 = requiredlist[j][2][1]

            totalsum += round(distance_function(lat1, lat2, lon1, lon2), 2)

            print(i, j)
            count += 1

print(round(totalsum, 2), totalsum, count)

# Closing file
f.close()

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS