def xchoice(iterable): ''' Randomly :term:`slice` off **one** items in `iterable`. :argument iterable: :term:`iterable` >>> from blade.xslice import xchoice >>> list(xchoice([1, 2, 3, 4, 5, 6])) # doctest: +SKIP 3 ''' i1, i2 = tee(iterable) return xat(i1, randrange(0, count(i2)))
def xinitial(iterable): ''' :term:`Slice` off every items in `iterable` except the **last** `iterable`. :argument iterable: :term:`iterable` :return: :term:`iterator` of items >>> from blade.xslice import xinitial >>> list(xinitial([5, 4, 3, 2, 1])) [5, 4, 3, 2] ''' i1, i2 = tee(iterable) return islice(i1, count(i2) - 1)
def xaverage(iterable): ''' Discover average value of numbers in `iterable`. :argument iterable: iterable object :return: a number >>> from blade.xmath import xaverage >>> xaverage([10, 40, 45]) 31.666666666666668 ''' i1, i2 = tee(iterable) return truediv(sum(i1, 0.0), count(i2))
def xsample(iterable, n): ''' Randomly :term:`slice` off `n` items in `iterable`. :argument iterable: :term:`iterable` :argument int n: sample size :return: :term:`iterator` of items >>> from blade.xslice import xsample >>> list(xsample([1, 2, 3, 4, 5, 6], 3)) # doctest: +SKIP [2, 4, 5] ''' i1, i2 = tee(iterable) return partmap( lambda i, r, c, x: i(x, r(0, c)), tee(i2, n), islice, randrange, count(i1), )
def xmedian(iterable): ''' Discover median value of numbers in `iterable`. :argument iterable: iterable object :return: a number >>> from blade.xmath import xmedian >>> xmedian([4, 5, 7, 2, 1]) 4 >>> xmedian([4, 5, 7, 2, 1, 8]) 4.5 ''' i1, i2 = tee(sorted(iterable)) result = truediv(count(i1) - 1, 2) pint = int(result) if result % 2 == 0: return xslicer(i2, pint) i3, i4 = tee(i2) return truediv(xslicer(i3, pint) + xslicer(i4, pint + 1), 2)
def xlast(iterable, n=0): ''' :term:`Slice` off `n` things from the **tail** end of items in `iterable` or just the **last** items in `iterable`. :argument iterable: :term:`iterable` :keyword int n: number of items in `iterable` to slice off :return: :term:`iterator` of items >>> from blade.xslice import xlast >>> # default behavior >>> list(xlast([5, 4, 3, 2, 1]))[0] 1 >>> # fetch last two things >>> list(xlast([5, 4, 3, 2, 1], 2)) [2, 1] ''' if n: i1, i2 = tee(iterable) return islice(i1, count(i2) - n, None) return iter(deferfunc(deque(iterable, maxlen=1).pop))
def test_count(self): from stuf.iterable import count self.assertEqual(count([1, 2, 3]), 3)