# implement County class here
class County:
def __init__(self, name,population,voters):
self.name=name
self.population=population
self.voters=voters
# implement the function here
def highest_turnout(data):
highest_turnout = (data[0].voters)/(data[0].population)
for county in data:
if (county.voters/county.population) > highest_turnout:
highest_turnout= county
return highest_turnout
allegheny = County("allegheny", 1000490, 645469)
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函数,在这个函数中返回最高的投票率我只是一个编程初学者,类资源并没有真正的帮助。任何帮助都将不胜感激。谢谢。在
方向:
●首先,使用对象的人口和选民属性,找出投票率最高的县,即投票人口的最高百分比
●然后,返回一个元组,其中包含投票率最高的县的名称和
按顺序投票的人口百分比;百分比应为
表示为0到1之间的数字
我已经写好了课。在
TypeError: '>' not supported between instances of 'float' and 'County'
我得到了这个错误。我认为我的类是正确的,但我不太确定如何处理这个函数。指示还说要以元组的形式返回县名和最高投票率,但我不太确定如何返回。请帮忙。非常感谢。在
你的问题是:
所以,让我们考虑一下这个循环的第一个迭代(好吧,第二个——关于
data[1]
的那个,因为data[0]
迭代在这里不相关)。highest_turnout
只是定义为选民/人口的float
。你把它和另一个国家的选民/人口相比较。有道理。在现在让我们考虑一下
voters / population
比data[0]
高。因此,if
条件被触发。highest_turnout
被设置为data[1]
,这是county
的当前值。在我们继续下一个迭代,对于
^{pr2}$data[2]
,您将得到错误:在第一次迭代中,
highest_turnout
是一个float
,您在两个floats
之间使用了运算符>
。但是现在,highest_turnout
是一个County
,而不是float
-当你在if
语句中给它分配一个新值时,你就改变了它的类型。由于County
不是一种数字类型,python不知道如何将其与float
进行比较。所以你在这里看到的错误。在解决方案是使
highest_turnout
成为被比较的值,而不是这些值来自的国家:另一种解决办法是将一个国家一直保留下来:
你只需要确保你没有在没有意识到的情况下改变任何变量的类型。在
或者,使用max函数,而不是使用循环来查找最大道岔县:
相关问题 更多 >
编程相关推荐