Отсортировать список стран двухпутевым слиянием python
Для примера взял поменьше стран. Нужно отсортировать их по заданному континенту и по численности населения. По численности я реализовал, а как сделать, чтобы и по континенту? Например только Азия и по численности населения.
class Country:
def __init__(self, make, continent, population):
self.make = make
self.continent = continent
self.population = population
def __str__(self):
return str.format("Country: {}, continent: {}, population: {}", self.make, self.continent,
self.population)
def merge(array, left_index, right_index, middle, comparison_function):
left_copy = array[left_index:middle + 1]
right_copy = array[middle+1:right_index+1]
left_copy_index = 0
right_copy_index = 0
sorted_index = left_index
while left_copy_index < len(left_copy) and right_copy_index < len(right_copy):
# We use the comparison_function instead of a simple comparison operator
if comparison_function(left_copy[left_copy_index], right_copy[right_copy_index]):
array[sorted_index] = left_copy[left_copy_index]
left_copy_index = left_copy_index + 1
else:
array[sorted_index] = right_copy[right_copy_index]
right_copy_index = right_copy_index + 1
sorted_index = sorted_index + 1
while left_copy_index < len(left_copy):
array[sorted_index] = left_copy[left_copy_index]
left_copy_index = left_copy_index + 1
sorted_index = sorted_index + 1
while right_copy_index < len(right_copy):
array[sorted_index] = right_copy[right_copy_index]
right_copy_index = right_copy_index + 1
sorted_index = sorted_index + 1
def merge_sort(array, left_index, right_index, comparison_function):
if left_index >= right_index:
return
middle = (left_index + right_index)//2
merge_sort(array, left_index, middle, comparison_function)
merge_sort(array, middle + 1, right_index, comparison_function)
merge(array, left_index, right_index, middle, comparison_function)
Country1 = Country("China", "Asia", 1273111)
Country2 = Country("India", "Asia", 1029991)
Country3 = Country("Japan", "Asia", 126771)
Country4 = Country("Russia", "Europe", 145567)
array = [Country1, Country2, Country3, Country4]
merge_sort(array, 0, len(array) -1, lambda CountryA, CountryB: CountryA.population <
CountryB.population)
print("Country sorted by population:")
for Country in array:
print(Country)