This notebook was prepared by Donne Martin. Source and license info is on GitHub.
Complexity:
from __future__ import division
class Solution(object):
def __init__(self, upper_limit=100):
self.max = None
self.min = None
# Mean
self.num_items = 0
self.running_sum = 0
self.mean = None
# Mode
self.array = [0] * (upper_limit + 1)
self.mode_occurrences = 0
self.mode = None
def insert(self, val):
if val is None:
raise TypeError('val cannot be None')
if self.max is None or val > self.max:
self.max = val
if self.min is None or val < self.min:
self.min = val
# Calculate the mean
self.num_items += 1
self.running_sum += val
self.mean = self.running_sum / self.num_items
# Calculate the mode
self.array[val] += 1
if self.array[val] > self.mode_occurrences:
self.mode_occurrences = self.array[val]
self.mode = val
%%writefile test_math_ops.py
import unittest
class TestMathOps(unittest.TestCase):
def test_math_ops(self):
solution = Solution()
self.assertRaises(TypeError, solution.insert, None)
solution.insert(5)
solution.insert(2)
solution.insert(7)
solution.insert(9)
solution.insert(9)
solution.insert(2)
solution.insert(9)
solution.insert(4)
solution.insert(3)
solution.insert(3)
solution.insert(2)
self.assertEqual(solution.max, 9)
self.assertEqual(solution.min, 2)
self.assertEqual(solution.mean, 5)
self.assertTrue(solution.mode in (2, 9))
print('Success: test_math_ops')
def main():
test = TestMathOps()
test.test_math_ops()
if __name__ == '__main__':
main()
Overwriting test_math_ops.py
%run -i test_math_ops.py
Success: test_math_ops