Python Forum
Determining the Percentage of Voter Population
Thread Rating:
  • 1 Vote(s) - 1 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Determining the Percentage of Voter Population
#1
Hi, I am struggling with this assignment. I am asked to determine which county has the highest voter percentage (in decimal form only, i.e. population in the county/voters in the county) in each of the given county below.

The assignment calls for the output and print statement of the tuple of the 'name of the county' and the 'voter percentage'.

I've already created my class 'County' and the function for calculating the percentage of voters in each of the county, and then compare the initial voter percentage with the first county withe rest of the county in the list ('data'). Once the voter percentage is compared and determined with the other county voter percentage as to which has the highest voter percentage, it is updated as that voter percentage with that population.

What is wrong with my function? How can I print a tuple with only the name of the county with its highest voter percentage?

class County:
  
  def __init__(self, name, population, voters):
    
    self.name = name
    self.population = population
    self.voters = voters
    
    def highest_turnout(data):
      
      people_county = data[0]
      total_people_county = data[0].population
      
      people_voted = data[0]
      total_number_voted = data[0].voters
      
      for County in data:
        
        voter_percentage = total_number_voted/total_people_population
        
        if voter_percentage > (data.voters/data.population):
          
          people_county = data
          total_people_county = data.population
          
          people_voted = data
          total_number_voted = data.voters
          
      return voter_percentage and total_people_voted
          
# 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)
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!

the format for each county in the given list is ('name of county', 'population', 'voters')
Reply
#2
I believe you misinterpret the assignment. The "highest_turnout()" function should not be part of the "County" class because the County class gives the definition how to create one county object. "highest_turnout()" should iterate over all counties so it is not logical to situate this function in the class.
In the first part the county-objects are created with:
allegheny = County("allegheny", 1000490, 645469)
et cetera
This uses only the __init__ function of the class.
After that a list is created of all county objects:
data = [allegheny, philadelphia, montgomery, lancaster, delaware, chester, bucks]
Then your function "highest_turnout()" is called:
result = highest_turnout(data) # do not change this line!
print(result) # prints the output of the function
So your assignment is to create a function with the following specifications:
  • The input is a list of objects
  • It will iterate over the list
  • From each county-object the name is extracted and a percentage is computed
  • The result of the function is not defined but it must be printable. So you may want to build up a string or create a list of rows.
Reply
#3
Hi I am still not clear what you mean by "the County class gives the definition how to create one county object"? Can you elaborate? Because the assignment starts off with this code:

# implement County class here
    
def highest_turnout(data) :

  # implement the function here

  return # modify this as needed

# 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)
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!
Reply
#4
Some hints.
If i run the code,i can loop over data like this.
>>> for country in data:
...     print(country.name, country.population, country.voters)
... 
allegheny 1000490 645469
philadelphia 1134081 539069
montgomery 568952 399591
lancaster 345367 230278
delaware 414031 284538
chester 319919 230823
If eg make this function for percentage.
def percentage(voters, population):
    return 100 * voters / population
>>> for country in data:
...     print(country.name, percentage(country.voters, country.population))
... 
allegheny 64.51528750912053
philadelphia 47.53355359978696
montgomery 70.23281401594511
lancaster 66.67631823538439
delaware 68.72383951926305
chester 72.15045058280377
bucks 72.0064662984719
So this is stuff that you can have in highest_turnout function.
Now can try find highest voter percentage in the loop,or collect data and use max() if that allowed.
Place this function highest_turnout outside of class,not in the class as you have in first code.
Can place a function in class,as just a function with using @staticmethod.
Reply
#5
The class should just do this: store the information given for one county, and calculate that county's voter percentage.

Then you create an instance of the class for each county, which will automatically get the voter percentages. Then you can use that information to find the largest voting percentage. If you've studied overriding special methods like __lt__ and __eq__, you can use those so that class instances sort themselves by voting percentage. Otherwise, you could do a sort with a key parameter to sort by the instances' voter percentage attribute.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#6
You can use the max function with lambda:
max(data, key=lambda vote: vote.voters / vote.population).name
Instead you could write it as a function, which is easier to unterstand.
def relative(country):
    return country.voters / country.population

max(data, key=relative).name
Just adding the calculated percentages to the class is a better solution.
from functools import total_ordering


@total_ordering
class County:
   
  def __init__(self, name, population, voters):
    self.name = name
    self.population = population
    self.voters = voters
    self.relative = voters / population
  def __lt__(self, other):
      return self.relative < other.relative
  def __gt__(self, other):
      return self.relative > other.relative
  def __eg__(self, other):
      return self.relative == other.relative
Now you can apply max on the data list. The function max returns the whole object from the list.
The total_ordering decorator modifies the class. It will create the missing comparisons like <= >= and !=.

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 = max(data)
print(result, type(result), result.name)
Output:
<__main__.County object at 0x7f6f47658610> <class '__main__.County'> chester
As you can see, the representation is missing. It could be added with the method __repr__, but it's not a must.
Dataclasses could do this automatically. Since Python 3.7 they are available.

from dataclasses import dataclass, field


@dataclass(order=True)
class County:
    name: str = field(compare=False)
    population: int = field(compare=False)
    voters: int = field(compare=False)
    relative: float = field(compare=True, default=0.0)
    def __post_init__(self):
        self.relative: float = self.voters / self.population
County('Test', 100, 1)
Output:
County(name='Test', population=100, voters=1, relative=0.01)
So it has also a nice presentation. In this case the relative value is set to 0.0.
After __post_init__ was called by dataclass itself,
the self.relative is overwritten with the calculated value.
You can also define how dataclasses are sorted.
For example you can make more then on field to compare, but you have to exclude other
fields, if they are not used for sorting. In this case relative is the only field to compare.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Linked List - Ordering by largest population with country name. PaleHorse 2 2,949 Jun-16-2020, 09:04 PM
Last Post: jefsummers
  finding percentage in a list. samh625 3 5,612 Jun-15-2020, 06:49 PM
Last Post: samh625
  Numerically determining the highest a ball travels when shot straight up JakeWitten 3 3,437 Apr-22-2017, 04:37 PM
Last Post: Ofnuts

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020