This repository has been archived by the owner on Nov 6, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validator.py
96 lines (71 loc) · 2.57 KB
/
validator.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
89
90
91
92
93
94
95
96
"""
This functions in this module perform validation to check that their inputs
of the needed types for this project.
"""
def is_vector(to_check):
"""
Checks if the argument is a single-leveled list, meaning that all of its
contents are one of three acceptable types: Int, Float, or String.
Args:
to_check (List): The list to check for vectorhood.
Returns:
Boolean.
Examples:
>>> w = [1.0, 2.0, 3.0]
>>> is_vector(w)
True
>>> x = [1, 2, 3]
>>> is_vector(x)
True
>>> y = ['a', 'b', 'c']
>>> is_vector(y)
True
>>> z = [1, 2, [1, 2]]
>>> is_vector(z)
False
"""
return all((isinstance(i, str) or
isinstance(i, int) or
isinstance(i, float))
for i in to_check)
def is_matrix(to_check):
"""
Checks if the argument is a valid matrix, meaning that each list within
the list is of the same length and and a valid type (Int, Float, String).
Args:
to_check (List): The list of lists to check for matrixhood.
Return:
A tuple where the first element indicates if the argument is a valid
matrix and the second is a (possibly empty) List of Strings containing
the problem messages to raise in the body of the error message.
Examples
>>> w = [ [1, 2, 3], [3, 2, 1] ]
>>> is_matrix(w)
(True, [])
>>> x = [ [1, 2, 3], ['a', 'b', 'c'] ]
>>> is_matrix(x)
(True, [])
>>> y = [ [1, 2, 3], ['a', 'b', 'c'], [1.0, 2.0, 3.0] ]
>>> is_matrix(y)
(True, [])
>>> z = [ [1, 2, 3], [3, 2] ]
>>> is_matrix(z)
(False, ['Each row must have the same number of columns.'])
>>> zz = [ [1, 2, 3], [3, 2, [3, 2]] ]
>>> is_matrix(zz)
(False, ['One of the rows in the matrix is not a valid vector.'])
>>> zzz = [ [1, 2, 3], [3, 2], [4, 5, [5, 4]] ]
>>> is_matrix(zzz) # doctest: +NORMALIZE_WHITESPACE
(False,
['One of the rows in the matrix is not a valid vector.',
'Each row must have the same number of columns.'])
"""
collector = []
if not all(is_vector(i) for i in to_check):
collector.append('One of the rows in the matrix is not ' +
'a valid vector.')
num_cols = len(to_check[0])
if any([len(a) != num_cols for a in to_check]):
collector.append('Each row must have the same number of columns.')
valid_matrix = not bool(collector)
return valid_matrix, collector