【发布时间】:2021-02-27 03:28:58
【问题描述】:
我对 Python 非常陌生,并且已经查看了有关此主题的其他三篇帖子,但未能成功实现它们。
基本上,我试图返回投票率最高的县的名称和百分比。我似乎无法弄清楚如何返回或打印后半部分,因为我没有数学部分(选民/人口)的属性。
我玩过一些类似的东西:
def percentage(self, turnout):
self.turnout = voters / population
抱歉,如果这篇文章格式不正确 - 这是全新的!提前致谢。
class County:
def __init__(self, name, population, voters):
self.name = name
self.population = population
self.voters = voters
def highest_turnout(data):
highest_county = data[0]
highest_percentage = (data[0].voters / data[0].population)
for county in data:
if (county.voters / county.population) > highest_percentage:
highest_county = county
highest_percentage = (county.voters / county.population)
return highest_county.name
# implement the function here
# your program will be evaluated using these objects
# it is okay to change/remove these lines but your program
# will be evaluated using these as inputs
allegheny = County("allegheny", 1000490, 645469) # this is an object
philadelphia = County("philadelphia", 1134081, 539069)
montgomery = County("montgomery", 568952, 399591)
lancaster = County("lancaster", 345367, 230278)
delaware = County("delaware", 414031, 284538)
chester = County("chester", 319919, 230823)
bucks = County("bucks", 444149, 319816)
data = [allegheny, philadelphia, montgomery, lancaster, delaware, chester, bucks]
result = highest_turnout(data) # do not change this line!
print(result) # prints the output of the function
# do not remove this line!
【问题讨论】:
标签: python object constructor