Soru
Part 2 (30pts) Write Python statements that will find the cities with maximum population and minimum population and print these cities with their respective populations, as seen in the sample run below. Part 2: City with maximum (37000000) City with minimum population: Antalya (1319000)
Çözüm
4.1248 Voting
Pamir
Usta · 5 yıl öğretmeniUzman doğrulaması
Cevap
To find the cities with the maximum and minimum populations, we need to read the data from a file and process it. Here is an example Python code that does this:<br />```python<br /># Open the file in read mode<br />with open('cities.txt', 'r') as file:<br /> # Read the lines from the file<br /> lines = file.readlines()<br /><br /># Create a dictionary to store the population of each city<br />city_populations = {}<br /><br /># Iterate through the lines and add the city and its population to the dictionary<br />for line in lines:<br /> city, population = line.strip().split(':')<br /> city_populations[city] = int(population)<br /><br /># Find the city with the maximum population<br />max_population = max(city_populations.values())<br />max_city = [city for city, population in city_populations.items() if population == max_population][0]<br /><br /># Find the city with the minimum population<br />min_population = min(city_populations.values())<br />min_city = [city for city, population in city_populations.items() if population == min_population][0]<br /><br /># Print the results<br />print(f"City with maximum population: {max_city} ({max_population})")<br />print(f"City with minimum population: {min_city} ({min_population})")<br />```<br />This code assumes that the file `cities.txt` contains one line for each city, in the format `City:Population`. For example, the line `Istanbul:37000000` represents the city Istanbul with a population of 37,000,000. The code reads the lines from the file, splits each line into the city and population, and stores them in a dictionary. It then finds the city with the maximum and minimum populations by finding the maximum and minimum values in the dictionary and using the `items()` method to get the corresponding city. Finally, it prints the results in the desired format.
Derecelendirmek için tıklayın: