1
1
from dataclasses import dataclass
2
- from typing import Any , Callable , Optional , TypeVar , cast
2
+ from typing import Any , Optional , TypeVar , cast
3
3
4
4
from reactivex import Observable , operators , typing
5
+ from reactivex .curry import curry_flip
5
6
6
7
_T = TypeVar ("_T" )
7
8
@@ -12,51 +13,47 @@ class AverageValue:
12
13
count : int
13
14
14
15
16
+ @curry_flip (1 )
15
17
def average_ (
18
+ source : Observable [Any ],
16
19
key_mapper : Optional [typing .Mapper [_T , float ]] = None ,
17
- ) -> Callable [[Observable [_T ]], Observable [float ]]:
18
- def average (source : Observable [Any ]) -> Observable [float ]:
19
- """Partially applied average operator.
20
+ ) -> Observable [float ]:
21
+ """Partially applied average operator.
20
22
21
- Computes the average of an observable sequence of values that
22
- are in the sequence or obtained by invoking a transform
23
- function on each element of the input sequence if present.
23
+ Computes the average of an observable sequence of values that
24
+ are in the sequence or obtained by invoking a transform
25
+ function on each element of the input sequence if present.
24
26
25
- Examples:
26
- >>> res = average(source)
27
+ Examples:
28
+ >>> res = average(source)
27
29
28
- Args:
29
- source: Source observable to average.
30
+ Args:
31
+ source: Source observable to average.
30
32
31
- Returns:
32
- An observable sequence containing a single element with the
33
- average of the sequence of values.
34
- """
33
+ Returns:
34
+ An observable sequence containing a single element with the
35
+ average of the sequence of values.
36
+ """
35
37
36
- key_mapper_ : typing .Mapper [_T , float ] = key_mapper or (
37
- lambda x : float (cast (Any , x ))
38
- )
38
+ key_mapper_ : typing .Mapper [_T , float ] = key_mapper or (
39
+ lambda x : float (cast (Any , x ))
40
+ )
39
41
40
- def accumulator (prev : AverageValue , cur : float ) -> AverageValue :
41
- return AverageValue (sum = prev .sum + cur , count = prev .count + 1 )
42
+ def accumulator (prev : AverageValue , cur : float ) -> AverageValue :
43
+ return AverageValue (sum = prev .sum + cur , count = prev .count + 1 )
42
44
43
- def mapper (s : AverageValue ) -> float :
44
- if s .count == 0 :
45
- raise Exception ("The input sequence was empty" )
45
+ def mapper (s : AverageValue ) -> float :
46
+ return s .sum / float (s .count )
46
47
47
- return s . sum / float ( s . count )
48
+ seed = AverageValue ( sum = 0 , count = 0 )
48
49
49
- seed = AverageValue (sum = 0 , count = 0 )
50
-
51
- ret = source .pipe (
52
- operators .map (key_mapper_ ),
53
- operators .scan (accumulator , seed ),
54
- operators .last (),
55
- operators .map (mapper ),
56
- )
57
- return ret
58
-
59
- return average
50
+ ret = source .pipe (
51
+ operators .map (key_mapper_ ),
52
+ operators .scan (accumulator , seed ),
53
+ operators .last (),
54
+ operators .map (mapper ),
55
+ )
56
+ return ret
60
57
61
58
62
59
__all__ = ["average_" ]
0 commit comments