Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/toolz/recipes.py: 56%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

9 statements  

1import itertools 

2from .itertoolz import frequencies, pluck, getter 

3 

4 

5__all__ = ('countby', 'partitionby') 

6 

7 

8def countby(key, seq): 

9 """ Count elements of a collection by a key function 

10 

11 >>> countby(len, ['cat', 'mouse', 'dog']) 

12 {3: 2, 5: 1} 

13 

14 >>> def iseven(x): return x % 2 == 0 

15 >>> countby(iseven, [1, 2, 3]) # doctest:+SKIP 

16 {True: 1, False: 2} 

17 

18 See Also: 

19 groupby 

20 """ 

21 if not callable(key): 

22 key = getter(key) 

23 return frequencies(map(key, seq)) 

24 

25 

26def partitionby(func, seq): 

27 """ Partition a sequence according to a function 

28 

29 Partition `s` into a sequence of lists such that, when traversing 

30 `s`, every time the output of `func` changes a new list is started 

31 and that and subsequent items are collected into that list. 

32 

33 >>> is_space = lambda c: c == " " 

34 >>> list(partitionby(is_space, "I have space")) 

35 [('I',), (' ',), ('h', 'a', 'v', 'e'), (' ',), ('s', 'p', 'a', 'c', 'e')] 

36 

37 >>> is_large = lambda x: x > 10 

38 >>> list(partitionby(is_large, [1, 2, 1, 99, 88, 33, 99, -1, 5])) 

39 [(1, 2, 1), (99, 88, 33, 99), (-1, 5)] 

40 

41 See also: 

42 partition 

43 groupby 

44 itertools.groupby 

45 """ 

46 return map(tuple, pluck(1, itertools.groupby(seq, key=func)))