livepython.net

247. Python Program to Count Votes and Find the Winner

MediumPhase 2 · Practice

A few steps, all with tools you know: a while loop, a dictionary and join().

Overview

A voting machine counts how many votes each person gets. Clubs, classes and shows all use this to pick a winner.

Problem Statement

Kwame's class votes for a class leader. Each vote is one name on its own line. Read the votes until a line says end. Then print:

  1. Every name and its number of votes, as <name>: <votes>, in the order the names first appeared.
  2. The result on the last line:
    • Winner: <name> when one name has the most votes.
    • Tie: <names> when two or more names share the most votes. List the tied names in the order they first appeared, with a comma and a space between them.

If there are no votes at all, print only No votes. Names must match exactly: Max and max are two different names.

Examples

Example 1. Input:

Asha
Ben
Asha
Carlos
Asha
Ben
end

gives:

Asha: 3
Ben: 2
Carlos: 1
Winner: Asha

Why: Asha has 3 votes, more than anyone else. The names are printed in the order they first came: Asha, then Ben, then Carlos.

Example 2. Input:

Ben
Asha
Asha
Ben
Dina
end

gives:

Ben: 2
Asha: 2
Dina: 1
Tie: Ben, Asha

Why: Ben and Asha both have 2 votes, so it is a tie. Ben's first vote came before Asha's, so Ben is listed first.

Input

One name per line, with no spaces in a name. The last line is always end, and it is not a vote. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.

Output

One line for each name, then the Winner: or Tie: line. Or only No votes. The tests try 7 different inputs, also no votes, one vote, a three-way tie and a winner who was not the first name.

Try it first. The solution opens when you solve this question, or after 3 tries with Submit.

Finish this chapter firstChapter 13 · Dictionaries
solution.py
# write your code here

EXPECTED OUTPUT

1Asha: 3
2Ben: 2
3Carlos: 1
4Winner: Asha

YOUR OUTPUT

Press Run to see your output here. Lines are compared with the expected output.