Count votes

New Programmer

Program to count votes for numerical options

3 bonuses 14 hints 36 solved

I'd like you to make a command-line program that accepts a file containing "votes" and prints the top-ranking votes.

Here's the scenario:

  1. I'm teaching a new workshop and I say "here are 5 optional topics we could discuss: please vote for what you're interested in hearing about by typing your votes into the chat window"
  2. Attendees type numbers in the chat window, sometimes voting for multiple options and sometimes just one option but no one ever types the same number twice (we're assuming honesty)
  3. I copy-paste this chat window output into a new file and run the program to see the topics ranked by popularity

Initially I'd like you to make a single function, called get_vote_tally, which works like this:

>>> get_vote_tally("Victor: 1 3 4\nPaul: 1 3\nAlex: 2 3 4\nMildred: 2 4\n")
[(3, [3, 4]), (2, [1, 2])]

The get_vote_tally function should return an iterable of 2-item tuples. The first item in each tuple represents a vote count and the second item is a list of choices that were voted for. So options 3 and 4 above received 3 votes each and options 1 and 2 received 2 votes each.

The tuples should be sorted by vote counts in descending order (so the highest counts show up first). The choice lists in each tuple should also be sorted with the lowest choice appearing first.

Multi-digit choices should also work as expected:

>>> get_vote_tally("""
... Mary:
... 40, 50
... Jessie:
... 40,20,30
... Gabriel:
... 30 20 & 50
... Ella:
... 10 20 40, but I'm fine with any
... Sarah:
... 20 30 50!!
... Read:
... 10 20 40
... 30 40 50 (from Meagan earlier in chat)
... """)
...
[(5, [20, 40]), (4, [30, 50]), (2, [10])]

Bonus 1


Trey Hunner

Want to solve this one?

Hi, I’m Trey, and I teach Python. Give this one a go, then I’ll show you how I’d solve it.

Sign up and solve it 7 days of All Access, no card needed