Files
troupe-standup/wizard-work/beam/test_stable_partition.py
T

46 lines
1.2 KiB
Python

import os
import random
from stable_partition import stable_partition
def test_empty():
assert stable_partition([], lambda x: True) == ([], [])
def test_all_true():
assert stable_partition([1, 2, 3], lambda x: True) == ([1, 2, 3], [])
def test_all_false():
assert stable_partition([1, 2, 3], lambda x: False) == ([], [1, 2, 3])
def test_mixed_preserves_order():
items = [1, 2, 3, 4, 5, 6]
yes, no = stable_partition(items, lambda x: x % 2 == 0)
assert yes == [2, 4, 6]
assert no == [1, 3, 5]
def test_none_items_raises():
try:
stable_partition(None, lambda x: True)
except TypeError:
return
raise AssertionError("expected TypeError")
def test_random_stability():
rng = random.Random(42)
for _ in range(200):
n = rng.randint(0, 30)
items = [rng.randint(0, 9) for _ in range(n)]
thr = rng.randint(0, 9)
yes, no = stable_partition(items, lambda x, t=thr: x >= t)
# membership
assert sorted(yes + no) == sorted(items)
# order preservation
iy = [i for i, x in enumerate(items) if x >= thr]
in_ = [i for i, x in enumerate(items) if x < thr]
assert [items[i] for i in iy] == yes
assert [items[i] for i in in_] == no