id/email
password
forgot password | create account
about | help | code help+videos | done | prefs
CodingBat code practice

 

peter@norvig.com > majority
prev  |  next  |  chance

Given a sequence of items (consider them votes for candidates), return the candidate with the majority of the votes. ("Majority" means more than half; that is stronger than "plurality," which means more than anyone else.) If no item has a majority, return None. Now you can solve the problem by going through the sequence once, keeping a running total for each candidate. That will solve the problem, but it requires storing a count for each candidate. There is a trickier way to do it so that, even if there are hundreds of candidates and million of votes, you only need to store one intermediate count, and one candidate at a time. (You don't need to find the tricky way to answer this question, but think about it and see if you can.)


majority('aaaccbbcccbcc') → 'c'
majority('ababa') → 'a'
majority('ababab') → None

...Save, Compile, Run (ctrl-enter)

def majority(items):

Editor font size %:
Shorter output


Forget It! -- delete my code for this problem

Progress graphs:
 Your progress graph for this problem
 Random user progress graph for this problem
 Random Epic Progress Graph

Python Help

Difficulty: 400 Post-solution available

Copyright Nick Parlante 2017 - privacy