Работа с задачей класса Python и проблема - PullRequest
0 голосов
/ 10 апреля 2020

Класс City имеет следующие атрибуты: имя, страна (где расположен город), высота (измеряется в метрах),

и численность населения (приблизительно, согласно последним статистическим данным). Заполните пробелы функции max_elevation_city

, чтобы вернуть название города и его страны (через запятую) при сравнении трех определенных экземпляров

для указанной минимальной группы населения. Например, вызов функции для минимального населения в 1 миллион:

max_elevation_city (1000000) должен вернуть «София, Болгария».

        # define a basic city class
class City:
    def __init__(self, name, country, elevation, population):
        self.name = name
        self.country = country
        self.elevation = elevation
        self.population = population

# create a new instance of the City class and
# define each attribute
city1 = City("Cusco","Peru",3399,358052)

# create a new instance of the City class and
# define each attribute
city2 = City("Sofia","Bulgaria",2290,1241675)

# create a new instance of the City class and
# define each attribute
city3 = City("Seoul","South Korea",38,9733509)

def max_elevation_city(min_population):
# Initialize the variable that will hold
# the information of the city with
# the highest elevation
    cities = [city1, city2, city3]
    lowest = None
    lowest_pop = 999999999
    for city in cities:
        if city.population >= min_population:
            if city.population <= lowest_pop:
                lowest = city
    if lowest != None:
        return lowest.name, lowest.country
    return ""

print(max_elevation_city(100000)) # Should print "Cusco, Peru"
print(max_elevation_city(1000000)) # Should print "Sofia, Bulgaria"
print(max_elevation_city(10000000)) # Should print ""

Ответы [ 3 ]

0 голосов
/ 13 апреля 2020

Спасибо всем, ниже приведено решение, как и ожидал Google:

class City:
   name = ""
   country = ""
   elevation = 0
   population = 0

# create a new instance of the City class and
# define each attribute
city1 = City()
city1.name = "Cusco"
city1.country = "Peru"
city1.elevation = 3399
city1.population = 358052

# create a new instance of the City class and
# define each attribute
city2 = City()
city2.name = "Sofia"
city2.country = "Bulgaria"
city2.elevation = 2290
city2.population = 1241675

# create a new instance of the City class and
# define each attribute
city3 = City()
city3.name = "Seoul"
city3.country = "South Korea"
city3.elevation = 38
city3.population = 9733509

def max_elevation_city(min_population):
   # Initialize the variable that will hold
# the information of the city with
# the highest elevation
   return_city = City()

   # Evaluate the 1st instance to meet the requirements:
   # does city #1 have at least min_population and
   # is its elevation the highest evaluated so far?
   if city1.population >= min_population and city1.elevation > return_city.elevation:
      return_city = city1
   # Evaluate the 2nd instance to meet the requirements:
   # does city #2 have at least min_population and
   # is its elevation the highest evaluated so far?
   if city2.population >= min_population and city2.elevation > return_city.elevation:
      return_city = city2
   # Evaluate the 3rd instance to meet the requirements:
   # does city #3 have at least min_population and
   # is its elevation the highest evaluated so far?
   if city3.population >= min_population and city3.elevation > return_city.elevation:
      return_city = city3

   #Format the return string
   if return_city.name:
      return ("{}, {}".format(return_city.name, return_city.country))
   else:
      return ""

print(max_elevation_city(100000)) # Should print "Cusco, Peru"
print(max_elevation_city(1000000)) # Should print "Sofia, Bulgaria"
print(max_elevation_city(10000000)) # Should print ""
0 голосов
/ 14 апреля 2020

А classi c вариант с классом и экземплярами:

# define a basic city class
class City:
    def __init__(self, name, country, elevation, population):
        self.name = name
        self.country = country
        self.elevation = elevation
        self.population = population


# create a new instance of the City class and
# define each attribute
city1 = City("Cusco", "Peru", 3399, 358052)

# create a new instance of the City class and
# define each attribute
city2 = City("Sofia", "Bulgaria", 2290, 1241675)

# create a new instance of the City class and
# define each attribute
city3 = City("Seoul", "South Korea", 38, 9733509)


def max_elevation_city(min_population):
    # Initialize the variable that will hold
    # the information of the city with
    # the highest elevation
    cities = [city1, city2, city3]
    lowest = None
    lowest_pop = 10000001
    for city in cities:
        if city.population >= min_population and city.population <= lowest_pop:
            if city.elevation >= city1.elevation or city.elevation >= city2.elevation or city.elevation >= city3.elevation:
                lowest = city
        if lowest != None:
            return ("{}, {}".format(lowest.name, lowest.country))
    return ""


print(max_elevation_city(100000))  # Should print "Cusco, Peru"
print(max_elevation_city(1000000))  # Should print "Sofia, Bulgaria"
print(max_elevation_city(10000000))  # Should print ""
0 голосов
/ 10 апреля 2020

Класс не настроен правильно. Это переменные класса, которые одинаковы для каждого экземпляра класса. Вы хотите переменные экземпляра, которые являются отдельными для каждого экземпляра. вот ссылка, чтобы узнать больше

Чтобы исправить

class City:
    def __init__(self, name, country,elevation, population)
        self.name = name
        self.country = country
        self.elevation = elevation
        self.population = population

Затем, чтобы создать новый экземпляр:

city1 = City("Cusco","Peru",3399,358052)

Вы все еще можете получить Атрибуты, выполнив

print(city1.name) # prints "Cusco"

Если вы сделаете их переменными класса следующим образом:

class City:
    name = ""
    country = ""
    elevation = 0
    population = 0

тогда при создании нового экземпляра:

city1 = City()
city1.name = "Cusco"
city1.country = "Peru"
city1.elevation = 3399
city1.population = 358052

# create a new instance of the City class and
# define each attribute
city2 = City()
city2.name = "Sofia"
city2.country = "Bulgaria"
city2.elevation = 2290
city2.population = 1241675

все они будут иметь одинаковые значения:

print(city1.name) #output 'Sophia'
print(city2.name) #output 'Sophia'

, поскольку вы изменили переменную во всех случаях


, как для функции, я бы сделал это:

def max_elevation_city(min_population):
    cities = [city1, city2, city3, city4]
        lowest = None
        lowest_pop = 999999999
        for city in cities:
            if city.population > min_population:
                if city.population < lowest_pop:
                    lowest = city
        if lowest != None:
            return lowest.name
        return ""
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...