Editor

First to the Top

Advanced · Stretch · from Python Dictionaries: The Complete Guide with Real Examples

From the lesson: Python Dictionaries: The Complete Guide with Real Examples

Open the contacts app on your phone. You look up a person by name and get their phone number. You don't search by position - you don't say "give me contact number 47." You search by name.

Read the lesson

Votes are counted one at a time. Write a function winner(votes) that takes the list of names in the order they were counted and returns the name with the most votes. When there is a tie, the name that reached that number of votes first wins. With no votes, return None.

winner(["ann", "bob", "ann"])                # 'ann'
winner(["kim", "bob", "bob", "kim", "cy"])   # 'bob'

In the second list kim and bob both get 2 votes, but bob reached 2 at the third vote and kim only at the fourth.

Return the answer instead of printing it: Check calls winner() with its own votes, some of them hidden.

def winner(votes):
pass
Solution unlocks after your first Check

What Check runs

Your code runs first, then each of these lines, and 5 more that stay hidden. The output must match exactly.

RunsExpected output
winner(["ann", "bob", "ann"])'ann'
winner(["kim", "lee", "lee", "kim", "lee"])'lee'

More Dictionary exercises

All Python exercises · 50 practice problems · Data Structures quiz