Skip to content

[Python] Challenge 7 (ReadyToMerge) #313

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 10, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions challenge_7/python/mindm/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Challenge_7
## Missing Number
This method will find the missing number in O(1) space and O(n) time!
Input is an unordered list from 0..n with 1 value missing.

You can run tests with:
```
$ python3 test.py
```
20 changes: 20 additions & 0 deletions challenge_7/python/mindm/src/missing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-


def find_missing(input_list):
""" Find the missing number in shuffled list
"""

# Mathematical formula for finding the sum of consequtive natural numbers
# (N*(N+1))/2
total = (len(input_list) * (len(input_list) +1)) / 2

summed = 0

for element in input_list:
summed += element

missing = total - summed

return missing
41 changes: 41 additions & 0 deletions challenge_7/python/mindm/src/test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
import random
from missing import find_missing


class TestDiff(unittest.TestCase):

def test_ordered(self):
self.assertEqual(find_missing([0,1,2,3,4,5,7]), 6)

def test_100_range(self):
big_range = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 65,
66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97,
98, 99]
random.shuffle(big_range)
self.assertEqual(find_missing(big_range), 64)

def test_empty(self):
self.assertEqual(find_missing([]), 0)

def test_minimal(self):
self.assertEqual(find_missing([0]), 1)

def test_small_unordered(self):
self.assertEqual(find_missing([3,0,1]), 2)

def test_huge_range_shuffled(self):
huge_range = list(range(1000))
random.shuffle(list(huge_range))
missing = huge_range.pop(random.randint(0,999))
self.assertEqual(find_missing(huge_range), missing)


if __name__ == '__main__':
unittest.main()