Skip to content

Instantly share code, notes, and snippets.

@blazs
Created April 25, 2018 12:38
Show Gist options
  • Save blazs/e4c625d35f21109562438c63461448ae to your computer and use it in GitHub Desktop.
Save blazs/e4c625d35f21109562438c63461448ae to your computer and use it in GitHub Desktop.
Playing around with Hypothesis package for property-based testing in Python
import functools
from hypothesis import given, strategies as st
def selection_sort(items):
items = list(items)
for idx, _ in enumerate(items, 0):
min_idx = idx
for jdx, item in enumerate(items[idx+1:], idx+1):
if item < items[min_idx]:
min_idx = jdx
items[idx], items[min_idx] = items[min_idx], items[idx]
return items
@given(st.lists(st.integers()).filter(lambda items: len(items) > 1))
def test_selection_sort(items):
sorted_items = selection_sort(items)
assert functools.reduce(
lambda P, Q: P and Q,
[sorted_items[idx-1] <= sorted_items[idx] for idx in range(1, len(sorted_items))]
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment