Problem Set 15: Simple Voting System

When you start a new problem set, your first instinct might be to open your computer and begin typing code right away. While this can feel productive, it often leads to frustration when things don't work as expected. Instead, take a few minutes to slow down and plan.

Here are some helpful strategies:

  1. Understand the problem clearly
    • Read the instructions carefully — twice if needed.
    • Ask yourself: What exactly is being asked?
  2. Break the problem into smaller steps
    • Think about the smallest possible actions the computer will need to perform.
    • For example: If the task is to find the first recurring letter in a word, what steps must happen first?
  3. Try solving it on paper first
    • Write out your steps in plain language (pseudocode).
    • Test your steps with a simple example before touching the keyboard.
  4. Translate your steps into code
    • Start small — write only a few lines at a time and test often.
    • Don't worry about perfection at first; get a working version, then improve it.
  5. Check your solution
    • Run it with different examples, including edge cases.
    • Ask: Does this solve the problem in all situations?

  • Read the question carefully (twice).
  • Break the task into the smallest steps.
  • Sketch or write pseudocode before coding.
  • Start small — test as you go.
  • Check your solution with different cases.

Overview:
In many elections, people vote for a candidate by writing their name. A simple voting system counts how many votes each candidate receives and then determines the winner.


Task 1: Count the Votes

Write a program that takes a list of votes (each vote is the name of a candidate) and counts how many votes each candidate received.

Example input:

votes = ["Alice", "Bob", "Alice", "Eve", "Bob", "Alice"]

Expected output:

Alice: 3
Bob: 2
Eve: 1

Task 2: Find the Winner

Extend your program to determine who won the election.

Expected output (using the list above):

The winner is Alice with 3 votes.

Task 3: Handle Ties

Modify your program so that if two or more candidates have the same highest number of votes, the program shows all of them.

Example input:

votes = ["Alice", "Bob", "Alice", "Bob"]

Expected output:

Alice: 2
Bob: 2
It is a tie between Alice and Bob!

Task 4: Test with an Empty List

What happens if the list of votes is empty ([])?
Update your program to print:

No votes cast.

Task 5: Invalid Votes

Sometimes people make mistakes. Assume only ["Alice", "Bob", "Eve"] are valid candidates. Update your program to ignore any other names.

Example input:

votes = ["Alice", "Bob", "Charlie", "Alice", "Eve", "Unknown"]

Expected output:

Alice: 2
Bob: 1
Eve: 1
Ignored votes: 2
The winner is Alice with 2 votes.

Testing Checklist

  • Program counts votes correctly for multiple candidates.
  • Program announces the correct winner.
  • Program handles ties.
  • Program handles no votes.
  • Program ignores invalid votes.