-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathoperations.py
More file actions
111 lines (87 loc) · 2.59 KB
/
Copy pathoperations.py
File metadata and controls
111 lines (87 loc) · 2.59 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
"""
A set of mathematical operations.
"""
class MathOperations:
def __init__(self, data):
self._data = data
def reorder_data(self):
"""
Reorder data in ascending order
"""
self._data.sort()
def find_max(self):
"""
Find maximum of all elements of a given list
Parameters
----------
data : list
List of data. Elements are numbers
Returns
-------
find_max : float
Maximum of list
"""
# Check that the input list has numbers
for n in self._data:
assert type(n) == int or type(n) == float
max_num = self._data[0] # Assume the first number is the maximum
for n in self._data:
if n > max_num:
max_num = n
return max_num
def find_median(self):
"""
Find median of all elements of a given list
Parameters
----------
data : list
List of data. Elements are numbers
Returns
-------
float : float
Median of list
"""
# Check that the input list has numbers
for n in self._data:
assert type(n) == int or type(n) == float
# Sort the data to find the median
sorted_data = sorted(self._data)
n = len(sorted_data)
# If odd number of elements, return the middle one
if n % 2 == 1:
return sorted_data[n // 2]
# If even number of elements, return the average of the two middle ones
else:
mid1 = sorted_data[n // 2 - 1]
mid2 = sorted_data[n // 2]
return (mid1 + mid2) / 2
def find_mean(self):
"""
Find mean of all elements of a given list
Parameters
----------
data : list
List of data. Elements are numbers
Returns
-------
float : float
Mean of list
"""
# Check that the input list has numbers
for n in self._data:
assert type(n) == int or type(n) == float
total = sum(self._data)
count = len(self._data)
mean = total / count
return mean
def main():
data = [5, 3, 14, 27, 4, 9, 53]
math_ops = MathOperations(data)
maximum = math_ops.find_max()
print("Maximum of {} is {}".format(data, maximum))
median = math_ops.find_median()
print("Median of {} is {}".format(data, median))
mean = math_ops.find_mean()
print("Mean of {} is {}".format(data, mean))
if __name__ == "__main__":
main()