Skip to content

Instantly share code, notes, and snippets.

@JosephSalisbury
Created November 19, 2014 15:39

Revisions

  1. JosephSalisbury created this gist Nov 19, 2014.
    36 changes: 36 additions & 0 deletions fill
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    """ Fill up a container, to some numerical limit, from another container
    dependent on some predicate between the item and the dependent
    container. """

    from itertools import takewhile
    import unittest


    def fill(source, destination, limit, predicate):

    iterator = source.__iter__()

    while len(destination) != limit:
    item = iterator.next()

    if predicate(destination, item):
    destination.append(item)

    class TestUniqueFill(unittest.TestCase):

    def setUp(self):

    self.source = ['a', 'c', 'a', 'b', 'a', 'c', 'd']
    self.destination = []

    def test_fill(self):

    fill(self.source, self.destination, 3, lambda d, i: i not in d)

    self.assertEquals(
    self.destination,
    ['a', 'c', 'b']
    )

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