-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathoperator_module.py
More file actions
84 lines (82 loc) · 1.06 KB
/
operator_module.py
File metadata and controls
84 lines (82 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
"""
It is convenient to use an arithmetic operator as a function
The operator module save you the trouble of writting trivial
anonymous functions like `lambda a, b: a * b`
>>> from functools import reduce
>>> import operator
>>> from operator import mul
>>> def fact1(n):
... return reduce(lambda a, b: a*b, range(1, n+1))
>>> def fact(n): # use mul
... return reduce(mul, range(1, n+1))
>>> mul(3, 4) # behaves like a function
12
>>> type(mul)
<class 'builtin_function_or_method'>
>>> fact1(5)
120
>>> fact(5)
120
# Have a look at what operator provides
>>> names = [name for name in dir(operator) if not name.startswith('_')]
>>> for name in names:
... print(name)
...
abs
add
and_
attrgetter
concat
contains
countOf
delitem
eq
floordiv
ge
getitem
gt
iadd
iand
iconcat
ifloordiv
ilshift
imatmul
imod
imul
index
indexOf
inv
invert
ior
ipow
irshift
is_
is_not
isub
itemgetter
itruediv
ixor
le
length_hint
lshift
lt
matmul
methodcaller
mod
mul
ne
neg
not_
or_
pos
pow
rshift
setitem
sub
truediv
truth
xor
"""
if __name__ == "__main__":
import doctest
doctest.testmod()