报这个错是因为 def tops(self, persons):里面忘记写self了
from collections import defaultdict 不要忘记import defaultdict
class TopVotedCandidate:
def tops(self, persons):
tops = []
voteCounts = defaultdict(int)
voteCounts[-1] = -1
top = -1
for p in persons:
voteCounts[p] += 1
# 在平局的情况下,最近获得投票的候选人将会获胜, 所以是>=
if voteCounts[p] >= voteCounts[top]:
top = p
tops.append(top)
#self.tops = tops
return tops
if __name__ == "__main__":
persons = [0,1,1,0,0,1,0]
# times = [0,5,10,15,20,25,30]
function = TopVotedCandidate()
print(function.tops(persons))