#!/usr/bin/env python # # Some of these are adapted from other djangosnippets. def has_consecutive_duplicates_of(seq, item): """Returns whether duplicate consecutive elements are in the sequence. Args: seq: The sequence. item: Which item to test for duplicates. >>> has_consecutive_duplicates_of([], 5) False >>> has_consecutive_duplicates_of([1, 2, 2, 3], 5) False >>> has_consecutive_duplicates_of([1, 2, 2, 3], 2) True >>> has_consecutive_duplicates_of([2, 0, 2], 2) False """ if not seq: return False for i in range(len(seq) - 1): if seq[i] == item and seq[i + 1] == item: return True return False def has_duplicates_of(seq, item): """Returns whether seq contains duplicates of the given item. Args: seq: The sequence. item: Which item to test for duplicates. >>> has_duplicates_of([], 5) False >>> has_duplicates_of([1, 2, 3], 5) False >>> has_duplicates_of([1, 2, 3], 2) False >>> has_duplicates_of([1, 2, 2, 3], 2) True """ return len(list(x for x in seq if x == item)) > 1 def count_items(seq, item): """Returns the number of times the given item appears in the sequence. Args: seq: The sequence. item: Which item to return the count of. >>> count_items([], 5) 0 >>> count_items([1, 2, 3], 5) 0 >>> count_items([1, 2, 3], 2) 1 >>> count_items([1, 2, 3, 2], 2) 2 """ return len(list(x for x in seq if x == item)) def slice(seq, count=2): """Splits a sequence into a list of count sublists. If count > len(seq) the returned list will still contain count sublists, but len(seq) - count of the sublists will be empty. From http://www.garyrobinson.net/2008/04/splitting-a-pyt.html Args: seq: The sequence. count: The number of sublists. >>> slice([], 2) [[], []] >>> slice([1, 2], 1) [[1, 2]] >>> slice([1, 2], 2) [[1], [2]] >>> slice(range(6), 2) [[0, 1, 2], [3, 4, 5]] >>> slice(range(5), 2) [[0, 1, 2], [3, 4]] >>> slice([1, 2], 3) [[1], [2], []] """ start = 0 output = [] for i in xrange(count): stop = start + len(seq[i::count]) output.append(seq[start:stop]) start = stop return output if __name__ == "__main__": import doctest doctest.testmod()