def omit(indices, from_, strict=False): """Returns a subsequence from given tuple, omitting specified indices. :param indices: Iterable of indices to exclude :param strict: Whether ``indices`` are required to exist in the tuple :return: Tuple without elements of specified indices :raise IndexError: If ``strict`` is True and one of ``indices`` is out of range. .. versionadded:: 0.0.3 """ from taipan.collections.sets import remove_subset ensure_iterable(indices) ensure_sequence(from_) if strict: remaining_indices = set(xrange(len(from_))) try: remove_subset(remaining_indices, indices) except KeyError as e: raise IndexError(int(str(e))) else: remaining_indices = set(xrange(len(from_))) - set(indices) return from_.__class__(from_[index] for index in remaining_indices)
def test_n__none(self): cycled = __unit__.cycle(self.ITERABLE) # iterate for a few cycles and check if elements match for i, elem in izip(xrange(self.LENGTH * self.CYCLES_COUNT), cycled): self.assertEquals(self.ITERABLE[i % self.LENGTH], elem) # make sure there is still some more for _ in xrange(self.CYCLES_COUNT): next(cycled)
def test_n__none(self): cycled = __unit__.cycle(self.ITERABLE) # iterate for a few cycles and check if elements match for i, elem in izip(xrange(self.LENGTH * self.CYCLES_COUNT), cycled): self.assertEquals(self.ITERABLE[i % self.LENGTH], elem) # make sure there is still some more for _ in xrange(self.CYCLES_COUNT): next(cycled)
def random(length, chars=None): """Generates a random string. :param length: Length of the string to generate. This can be a numbe or a pair: ``(min_length, max_length)`` :param chars: String of characters to choose from """ if chars is None: chars = string.ascii_letters + string.digits else: ensure_string(chars) if not chars: raise ValueError("character set must not be empty") if is_pair(length): length = randint(*length) elif isinstance(length, Integral): if not length > 0: raise ValueError("random string length must be positive (got %r)" % (length, )) else: raise TypeError("random string length must be an integer; " "got '%s'" % type(length).__name__) return join(chars.__class__(), (choice(chars) for _ in xrange(length)))
def random(length, chars=None): """Generates a random string. :param length: Length of the string to generate. This can be a numbe or a pair: ``(min_length, max_length)`` :param chars: String of characters to choose from """ if chars is None: chars = string.ascii_letters + string.digits else: ensure_string(chars) if not chars: raise ValueError("character set must not be empty") if is_pair(length): length = randint(*length) elif isinstance(length, Integral): if not length > 0: raise ValueError( "random string length must be positive (got %r)" % (length,)) else: raise TypeError("random string length must be an integer; " "got '%s'" % type(length).__name__) return join(chars.__class__(), (choice(chars) for _ in xrange(length)))
def _get_override_base(self, override_wrapper): """Retrieve the override base class from the :class:`_OverriddenMethod` wrapper. """ base = override_wrapper.modifier.base if not base: return None if is_class(base): return base # resolve the (possibly qualified) class name if '.' in base: # repeatedly try to import the first N-1, N-2, etc. dot-separated # parts of the qualified name; this way we can handle all names # including `package.module.Class.InnerClass` dot_parts = base.split('.') for i in xrange(len(dot_parts) - 1, 1, -1): # n-1 -> 1 module_name = '.'.join(dot_parts[:i]) class_name = '.'.join(dot_parts[i:]) try: module = __import__(module_name, fromlist=[dot_parts[i]]) break except ImportError: pass else: # couldn't resolve class name, return it verbatim return base else: class_name = base module_name = override_wrapper.method.__module__ module = sys.modules[module_name] return getattr(module, class_name)
class Power(_SubsetGeneration): POWERSET_OF_TWO_ELEMS_TUPLE = [(), (1, ), (2, ), (1, 2)] POWERSET_OF_TWO_ELEMS_SET = [set(), set([1]), set([2]), set([1, 2])] EIGHT_ELEMS_TUPLE = tuple(xrange(8)) EIGHT_ELEMS_SET = set(xrange(8)) def test_none(self): with self.assertRaises(TypeError): __unit__.power(None) def test_some_object(self): with self.assertRaises(TypeError): __unit__.power(object()) def test_empty_iterable(self): self.assertItemsEqual([()], __unit__.power([])) def test_singleton_iterable(self): self.assertItemsEqual([(), (42, )], __unit__.power([42])) def test_empty_set(self): self.assertItemsEqual([set()], __unit__.power(set())) def test_singleton_set(self): set_ = set([42]) self.assertItemsEqual([set(), set_], __unit__.power(set_)) def test_cardinality2_iterable(self): self.assertItemsEqual(self.POWERSET_OF_TWO_ELEMS_TUPLE, __unit__.power(self.TWO_ELEMS_TUPLE)) def test_cardinality2_set(self): self.assertItemsEqual(self.POWERSET_OF_TWO_ELEMS_SET, __unit__.power(self.TWO_ELEMS_SET)) def test_cardinality8_iterable__just_count(self): powerset = list(__unit__.power(self.EIGHT_ELEMS_TUPLE)) self.assertAll(is_tuple, powerset) self.assertEquals(2**len(self.EIGHT_ELEMS_TUPLE), len(powerset)) def test_cardinality8_set__just_count(self): powerset = list(__unit__.power(self.EIGHT_ELEMS_SET)) self.assertAll(is_set, powerset) self.assertEquals(2**len(self.EIGHT_ELEMS_SET), len(powerset))
def test_pad__custom(self): padded = __unit__.pad(self.ITERABLE, with_=self.PADDING) self._assertGenerator(padded) for i, elem in izip(xrange(self.MUCH_MORE_THAN_LENGTH), padded): if i < self.LENGTH: self.assertIs(self.ITERABLE[i], elem) else: self.assertIs(self.PADDING, elem)
def test_pad__default(self): padded = __unit__.pad(self.ITERABLE) self._assertGenerator(padded) for i, elem in izip(xrange(self.MUCH_MORE_THAN_LENGTH), padded): if i < self.LENGTH: self.assertIs(self.ITERABLE[i], elem) else: self.assertIsNone(elem)
def test_pad__default(self): padded = __unit__.pad(self.ITERABLE) self._assertGenerator(padded) for i, elem in izip(xrange(self.MUCH_MORE_THAN_LENGTH), padded): if i < self.LENGTH: self.assertIs(self.ITERABLE[i], elem) else: self.assertIsNone(elem)
def test_pad__custom(self): padded = __unit__.pad(self.ITERABLE, with_=self.PADDING) self._assertGenerator(padded) for i, elem in izip(xrange(self.MUCH_MORE_THAN_LENGTH), padded): if i < self.LENGTH: self.assertIs(self.ITERABLE[i], elem) else: self.assertIs(self.PADDING, elem)
def test_n__positive(self): cycled = __unit__.cycle(self.ITERABLE, self.CYCLES_COUNT) # iterate for an exactly the expected number of elements for i, elem in izip(xrange(self.LENGTH * self.CYCLES_COUNT), cycled): self.assertEquals(self.ITERABLE[i % self.LENGTH], elem) # make sure the cycled iterable has been exhausted this way with self.assertRaises(StopIteration): next(cycled)
def test_n__positive(self): cycled = __unit__.cycle(self.ITERABLE, self.CYCLES_COUNT) # iterate for an exactly the expected number of elements for i, elem in izip(xrange(self.LENGTH * self.CYCLES_COUNT), cycled): self.assertEquals(self.ITERABLE[i % self.LENGTH], elem) # make sure the cycled iterable has been exhausted this way with self.assertRaises(StopIteration): next(cycled)
def _assertIntegerFunctionsEqual(self, f, g, argcount=1, domain=None): if domain is None: # use roughly the same amount time regardless of function's arity limit = int(pow(512, 1.0 / argcount)) self.assertGreater( limit, 0, msg="Too many arguments for integer functions") domain = xrange(-limit, limit + 1) for args in product(domain, repeat=argcount): self.assertEquals(f(*args), g(*args), msg="result mismatch for args: %r" % (args,))
def power(set_): """Returns all subsets of given set. :return: Powerset of given set, i.e. iterable containing all its subsets, sorted by ascending cardinality. """ ensure_countable(set_) result = chain.from_iterable(combinations(set_, r) for r in xrange(len(set_) + 1)) return _harmonize_subset_types(set_, result)
def _assertIntegerFunctionsEqual(self, f, g, argcount=1, domain=None): if domain is None: # use roughly the same amount time regardless of function's arity limit = int(pow(512, 1.0 / argcount)) self.assertGreater(limit, 0, msg="Too many arguments for integer functions") domain = xrange(-limit, limit + 1) for args in product(domain, repeat=argcount): self.assertEquals(f(*args), g(*args), msg="result mismatch for args: %r" % (args, ))
class Cycle(_Algorithm): LENGTH = 10 ITERABLE = list(xrange(LENGTH)) CYCLES_COUNT = 64 def test_iterable__none(self): with self.assertRaises(TypeError): __unit__.cycle(None) def test_iterable__some_object(self): with self.assertRaises(TypeError): __unit__.cycle(object()) def test_iterable__empty(self): cycled = __unit__.cycle(()) self.assertEmpty(cycled, msg="cycled empty iterable expected to be also empty") def test_n__none(self): cycled = __unit__.cycle(self.ITERABLE) # iterate for a few cycles and check if elements match for i, elem in izip(xrange(self.LENGTH * self.CYCLES_COUNT), cycled): self.assertEquals(self.ITERABLE[i % self.LENGTH], elem) # make sure there is still some more for _ in xrange(self.CYCLES_COUNT): next(cycled) def test_n__zero(self): cycled = __unit__.cycle(self.ITERABLE, 0) self.assertEmpty(cycled, msg="iterable cycled 0 times expected to be empty") def test_n__negative(self): with self.assertRaises(ValueError): __unit__.cycle(self.ITERABLE, -1) def test_n__positive(self): cycled = __unit__.cycle(self.ITERABLE, self.CYCLES_COUNT) # iterate for an exactly the expected number of elements for i, elem in izip(xrange(self.LENGTH * self.CYCLES_COUNT), cycled): self.assertEquals(self.ITERABLE[i % self.LENGTH], elem) # make sure the cycled iterable has been exhausted this way with self.assertRaises(StopIteration): next(cycled)
def intercalate(elems, list_): """Insert given elements between existing elements of a list. :param elems: List of elements to insert between elements of ``list_` :param list_: List to insert the elements to :return: A new list where items from ``elems`` are inserted between every two elements of ``list_`` """ ensure_sequence(elems) ensure_sequence(list_) if len(list_) <= 1: return list_ return sum( (elems + list_[i:i+1] for i in xrange(1, len(list_))), list_[:1])
class Pad(_Algorithm): LENGTH = 10 ITERABLE = list(xrange(LENGTH)) MUCH_MORE_THAN_LENGTH = 100 * LENGTH PADDING = object() def test_iterable__none(self): with self.assertRaises(TypeError): __unit__.pad(None) def test_iterable__some_object(self): with self.assertRaises(TypeError): __unit__.pad(object()) def test_iterable__empty(self): padded = __unit__.pad([]) self._assertGenerator(padded) for _, elem in izip(xrange(self.MUCH_MORE_THAN_LENGTH), padded): self.assertIsNone(elem) def test_pad__default(self): padded = __unit__.pad(self.ITERABLE) self._assertGenerator(padded) for i, elem in izip(xrange(self.MUCH_MORE_THAN_LENGTH), padded): if i < self.LENGTH: self.assertIs(self.ITERABLE[i], elem) else: self.assertIsNone(elem) def test_pad__custom(self): padded = __unit__.pad(self.ITERABLE, with_=self.PADDING) self._assertGenerator(padded) for i, elem in izip(xrange(self.MUCH_MORE_THAN_LENGTH), padded): if i < self.LENGTH: self.assertIs(self.ITERABLE[i], elem) else: self.assertIs(self.PADDING, elem)
class Peek(TestCase): SET = set(xrange(3)) def test_none(self): with self.assertRaises(TypeError): __unit__.peek(None) def test_some_object(self): with self.assertRaises(TypeError): __unit__.peek(object()) def test_non_set_iterable(self): with self.assertRaises(TypeError): __unit__.peek([42]) def test_set__empty(self): with self.assertRaises(KeyError): __unit__.peek(set()) def test_set__normal(self): element = __unit__.peek(self.SET) self.assertIn(element, self.SET)
def test_iterable__empty(self): padded = __unit__.pad([]) self._assertGenerator(padded) for _, elem in izip(xrange(self.MUCH_MORE_THAN_LENGTH), padded): self.assertIsNone(elem)
def test_iterable__infinite__multiple_calls(self): counter = self.Counter() for i in xrange(1, self.FEW): __unit__.iterate(counter, self.FEW) self.assertEquals(i * self.FEW, counter.current_count)
def test_iterable__empty(self): padded = __unit__.pad([]) self._assertGenerator(padded) for _, elem in izip(xrange(self.MUCH_MORE_THAN_LENGTH), padded): self.assertIsNone(elem)
def test_iterable__infinite__multiple_calls(self): counter = self.Counter() for i in xrange(1, self.FEW): __unit__.iterate(counter, self.FEW) self.assertEquals(i * self.FEW, counter.current_count)