1.我正在解决一个关于coursera的练习论文,我就是不能解决这个问题,有人能帮忙吗?
1.显然,面向对象编程的主题在那门课程中是可选的,所以它是不是不重要或者不够有用?
问题是这样的:
“City类具有以下属性:名称、国家/地区(城市所在地)、海拔(以米为单位)和人口(根据最近的统计数据得出的近似值)。在比较指定的最小人口数的3个已定义示例时,填充max_elevation_city函数的空白以返回城市及其国家/地区的名称(用逗号分隔)。例如,针对最小人口数为100万的情况调用函数:max_elevation_city(1000000)应返回“保加利亚索菲亚”。
# define a basic city class
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 ___
return_city = ___
# 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 ___
return_city = ___
# 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 ___
return_city = ___
#Format the return string
if return_city.name:
return ___
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 ""
8条答案
按热度按时间czfnxgou1#
下面的代码段就可以做到这一点:
首先,
if
检查city 1是否超过给定的最小人口数。由于我们知道return_city
尚未设置,因此不需要检查海拔是否最大。第二个和第三个
if
检查相同的情况,但如果高程大于先前设置的高程,则进行额外检查。在return语句中,我们使用f string来格式化。
我想知道你到底被困在哪里了,因为这里没有发生OOP魔法。
关于您提出的OOP是否重要的问题:一如既往--这取决于!了解python中的OOP将给予你更深入地理解python是如何工作的,而OOP通常在许多项目中是有帮助的。但是如果你只想将python用作脚本语言,你就不需要太多的OOP知识。
8oomwypt2#
您还可以使用此
3htmauhk3#
50few1ms4#
ev7lccsx5#
soat7uwm6#
您可以像这样简化解决方案
我们确保城市拥有所需的最低人口数,并且拒绝之前的城市要求
我们确保城市拥有所需的最低人口数,并且拒绝之前的城市要求
l0oc07j27#
ekqde3dh8#