Skip to content

Instantly share code, notes, and snippets.

@intuited
Created October 10, 2010 03:08
Show Gist options
  • Save intuited/618883 to your computer and use it in GitHub Desktop.
Save intuited/618883 to your computer and use it in GitHub Desktop.
"""
>>> from copy import deepcopy
>>> pred = lambda v: v <= 2
>>> test_list = [1, 2, 1, 3, 1, 2, 4, 2, 3, 1]
>>> correct = [1, 2, 1, 1, 2, 2, 1]
... # the values from the list which are less than or equal to 2
>>> def dotest(cull, lst, pred):
... lst = deepcopy(lst)
... cull(lst, pred)
... return lst
>>> dotest(shawley_cull_list, test_list, pred)
[1, 2, 1, 1, 2, 2, 1]
>>> dotest(cull_list, test_list, pred)
[1, 2, 1, 1, 2, 2, 1]
>>> pred = lambda v: v > 2
>>> correct = [3, 4, 3] # The values from the list that are greater than 2
>>> dotest(shawley_cull_list, test_list, pred)
[2, 3, 2, 4, 3]
>>> dotest(cull_list, test_list, pred)
[3, 4, 3]
>>> dotest(genexp_cull_list, test_list, pred)
[3, 4, 3]
>>> dotest(user_cull_list, test_list, pred)
[3, 2, 4, 2, 3]
>>> test_list = [1, 2, 3, 4, 5, 6]
>>> pred = lambda v: v <= 2
>>> dotest(shawley_cull_list, test_list, pred)
[1, 2, 4, 6]
>>> dotest(user_cull_list, test_list, pred)
[1, 2, 4, 6]
>>> dotest(cull_list, test_list, pred)
[1, 2]
>>> dotest(efficient_cull_list, test_list, pred)
[1, 2]
>>> dotest(genexp_cull_list, test_list, pred)
[1, 2]
"""
def shawley_cull_list(lst, my_predicate):
for idx, val in enumerate(lst):
if not my_predicate(val):
del(lst[idx])
def cull_list(lst, pred):
"""Removes all values from ``lst`` which for which ``pred(v)`` is false."""
def remove_all(v):
"""Remove all instances of ``v`` from ``lst``"""
try:
while True:
lst.remove(v)
except ValueError:
pass
values = set(lst)
for v in values:
if not pred(v):
remove_all(v)
def user_cull_list(lst, pred):
for n, x in enumerate(lst):
if not pred(x): lst.remove(x)
def efficient_cull_list(lst, pred):
end = len(lst)
i = 0
while i < end:
if not pred(lst[i]):
del lst[i]
end -= 1
else:
i += 1
def genexp_cull_list(lst, pred):
lst[:] = (v for v in lst if pred(v))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment