-
Notifications
You must be signed in to change notification settings - Fork 2
/
useful_functions.py
88 lines (69 loc) · 1.77 KB
/
useful_functions.py
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
85
86
87
88
#!/usr/bin/env python
import re
def isprime(n):
'''
>>> for n in inclusive_range(0, 10):
... print('{0} is prime: {1}'.format(n, isprime(n)))
...
0 is prime: False
1 is prime: False
2 is prime: True
3 is prime: True
4 is prime: False
5 is prime: True
6 is prime: False
7 is prime: True
8 is prime: False
9 is prime: False
10 is prime: False
'''
if n in [0, 1]:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
def inclusive_range(start=0, stop=0, step=1):
'''
>>> list(inclusive_range(-10, 10, 2))
[-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10]
'''
_range = list(range(start, stop, step))
_range.append(stop)
return iter(_range)
def valid_email(email):
'''
>>> valid_email('[email protected]')
True
>>> valid_email('[email protected]')
False
'''
match = re.search(r'(^[a-zA-Z0-9\.\+_-]+)@[a-zA-Z].[a-zA-Z\.]+$', email)
if match:
return True
return False
def binary_addition(*args):
'''
>>> binary_addition(2, 13)
'1111'
>>> binary_addition(2, 13, 4, 77)
'1100000'
'''
return bin(sum(args))[2:]
def odds(list):
'''
Returns all odd members of a list in the same order they appeared in it.
>>> odds([1,2,3,4,5,6,7,8,9,10])
[1, 3, 5, 7, 9]
'''
return [i for i in list if i % 2 == 1]
def evens(list):
'''
Returns all even members of a list in the same order they appeard in it.
>>> evens([1,2,3,4,5,6,7,8,9,10])
[2, 4, 6, 8, 10]
'''
return [i for i in list if i % 2 == 0]
if __name__ == "__main__":
import doctest
doctest.testmod()