Last active
August 3, 2017 12:26
-
-
Save matthiasgoergens/a41fb998d2b087658c1d304494f63ce7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/local/bin/python3.6 | |
# -*- coding: utf-8 -*- | |
from hypothesis import given, example | |
import hypothesis.strategies as st | |
def linear_search(key, l): | |
"""Given a search key and a list of tuples (key, value), return | |
the first item that matches the key, or None if none match. | |
Example: | |
linear_search(1, [(0, "a"), (1, "b"), (6, "c")]) == "b" | |
linear_search(5, [(0, "a"), (1, "b"), (6, "c")]) == None | |
""" | |
for k, item in l: | |
if k == key: | |
return item | |
else: | |
return None | |
def binary_search(key, l): | |
"""Given a search key and a list of tuples (key, value) sorted by key, return | |
the first item that matches the key, or None if none match. Uses binary search. | |
You can assume keys are ints. | |
Example: | |
binary_search(1, [(0, "a"), (1, "b"), (6, "c")]) == "b" | |
binary_search(5, [(0, "a"), (1, "b"), (6, "c")]) == None | |
""" | |
raise NotImplementedError("Binary search not implemented.") | |
@given(k=st.integers(), l=st.lists(st.tuples(st.integers(), st.text())).map(sorted)) | |
def test_reference_implementation(k, l): | |
"""Test that binary search gives the same result as linear search on a sorted list.""" | |
linear = linear_search(k, l) | |
binary = binary_search(k, l) | |
assert linear == binary, "{} != {}".format(repr(linear), repr(binary)) | |
@given(k=st.integers(), l=st.lists(st.tuples(st.integers(), st.text()), unique_by=(lambda kv:kv[0])).map(sorted)) | |
def test_reference_implementation_uniq(k, l): | |
"""Test that binary search gives the same result as linear search on a sorted list.""" | |
linear = linear_search(k, l) | |
binary = binary_search(k, l) | |
assert linear == binary, "{} != {}".format(repr(linear), repr(binary)) | |
if __name__ == '__main__': | |
print("Uniq keys only:") | |
test_reference_implementation_uniq() | |
print("Allow repeated keys:") | |
test_reference_implementation() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It shows you that the smallest counterexample is
test_reference_implementation_uniq(k=0, l=[])
(which is super-simple, since we haven't implemented anything yet).