-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.mjs
50 lines (39 loc) · 1.53 KB
/
main.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import requests
def findCountry(region, keyword):
base_url = f"https://jsonmock.hackerrank.com/api/countries/search"
params = {
"region": region,
"name": keyword,
}
all_countries = []
response = requests.get(base_url, params=params)
if response.status_code == 200:
data = response.json()
all_countries.extend(data.get('data', []))
total_pages = data.get('total_pages', 1)
# Fetch data from other pages if available
for page in range(2, total_pages + 1):
params['page'] = page
response = requests.get(base_url, params=params)
if response.status_code == 200:
data = response.json()
all_countries.extend(data.get('data', []))
return all_countries
else:
print(f"Error: Unable to fetch data. Status code: {response.status_code}")
return None
def main():
region = input("Enter the region: ")
keyword = input("Enter the keyword: ")
country_data = findCountry(region, keyword)
if country_data:
# Sort the countries by population first and then by name
sorted_countries = sorted(country_data, key=lambda x: (x['population'], x['name']))
for country in sorted_countries:
name = country.get('name', 'Unknown Country')
population = country.get('population', 'Unknown Population')
print(f"{name},{population}")
else:
print("No data found for the given region and keyword.")
if _name_ == "_main_":
main()