0

How to create function which iterates over each county, calculating voter turnout percentage?

class County:  
    def __init__(self, init_name, init_population, init_voters) :  
        self.name = init_name  
        self.population = init_population  
        self.voters = init_voters   

def highest_turnout(data) :  

    100 * (self.voters / self.population)

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]  

1 Answers1

0

Your class County is defined correctly. However, function county is not correct.

When passing data in the function highest_turnout, you have to first calculate the percentage of voters in the first County of the list - it is positioned at data[0]. Then we set “highest” to be the country name of the 1st County, we assume that the 1st in the data list is the highest one we have seen.

Next, we use a for loop to start iterating over all the County objects in the list data in order to pass in each County object.

The variable pct gives us the percentage of voters in the County that is running in the current step. The if function compares it to the highest percentage stored in the variable pct. If the new percentage is higher than pct (returns True), we update the highest percentage variable pct and hence update the county name.

def highest_turnout(data) :

  highest_pct = data[0].voters / data[0].population
  highest = data[0].name

  for county in data :
    pct = county.voters / county.population
    if pct > highest_pct :
      highest_pct = pct
      highest = county.name
rabbithole
  • 11
  • 3