Skip to content

Instantly share code, notes, and snippets.

@msolomon
Created December 6, 2012 23:02
Show Gist options
  • Select an option

  • Save msolomon/4229286 to your computer and use it in GitHub Desktop.

Select an option

Save msolomon/4229286 to your computer and use it in GitHub Desktop.
score keeping interview problem
# Mike Solomon
class ScoreKeeper(object):
def __init__(self):
self.scores = [0] * 100
self.total = 0 # total scores inserted
self.curr_median = None # current value of median
self.curr_left_of = 0 # number of scores inserted < current median
self.curr_right_of = 0 # number of scores inserted > current median
def submit(self, score):
"""Takes a score and saves it."""
if score < 0 or score > 99:
raise InvalidScoreException() # TODO: implement exception
self.scores[score] += 1
self.total += 1
if self.curr_median is None: # first insert
self.curr_median = score
elif score < self.curr_median:
self.curr_left_of += 1
if self.curr_left_of >= self.scores[self.curr_median] + self.curr_right_of:
# median changed: somewhere to left of current median
self.find_median()
elif score > self.curr_median:
self.curr_right_of += 1
if self.curr_right_of > self.scores[self.curr_median] + self.curr_left_of:
# median changed: somewhere to right of current median
self.find_median()
def find_median(self):
""" Calculate the median """
ttl = 0
for i, score in enumerate(self.scores):
ttl += score
if ttl >= self.total / 2.:
self.curr_median = i
self.curr_left_of = ttl - score
self.curr_right_of = self.total - ttl
break
def median(self):
"""Returns the left median of all scores submitted so far."""
return self.curr_median
sk = ScoreKeeper()
sk.submit(1)
print 'should be 1:', sk.median()
sk.submit(2)
print 'should be 1:', sk.median()
sk.submit(2)
print 'should be 2:', sk.median()
sk.submit(0)
print 'should be 1:', sk.median()
sk.submit(99)
print 'should be 2:', sk.median()
sk.submit(55)
print 'should be 2:', sk.median()
for _ in range(10):
sk.submit(0)
print 'should be 0:', sk.median()
print sk.scores
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment