|
1 |
| -import statistics |
2 |
| - |
3 |
| - |
4 |
| -def mode(input_list): # Defining function "mode." |
| 1 | +def mode(input_list: list) -> list: # Defining function "mode." |
5 | 2 | """This function returns the mode(Mode as in the measures of
|
6 | 3 | central tendency) of the input data.
|
7 | 4 |
|
8 | 5 | The input list may contain any Datastructure or any Datatype.
|
9 | 6 |
|
10 | 7 | >>> input_list = [2, 3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 2, 2, 2]
|
11 | 8 | >>> mode(input_list)
|
12 |
| - 2 |
13 |
| - >>> input_list = [2, 3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 2, 2, 2] |
14 |
| - >>> mode(input_list) == statistics.mode(input_list) |
15 |
| - True |
| 9 | + [2] |
| 10 | + >>> input_list = [3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 4, 2, 2, 2] |
| 11 | + >>> mode(input_list) |
| 12 | + [2] |
| 13 | + >>> input_list = [3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 4, 4, 2, 2, 4, 2] |
| 14 | + >>> mode(input_list) |
| 15 | + [2, 4] |
| 16 | + >>> input_list = ["x", "y", "y", "z"] |
| 17 | + >>> mode(input_list) |
| 18 | + ['y'] |
| 19 | + >>> input_list = ["x", "x" , "y", "y", "z"] |
| 20 | + >>> mode(input_list) |
| 21 | + ['x', 'y'] |
16 | 22 | """
|
17 |
| - # Copying input_list to check with the index number later. |
18 |
| - check_list = input_list.copy() |
19 | 23 | result = list() # Empty list to store the counts of elements in input_list
|
20 | 24 | for x in input_list:
|
21 | 25 | result.append(input_list.count(x))
|
22 |
| - input_list.remove(x) |
23 |
| - y = max(result) # Gets the maximum value in the result list. |
24 |
| - # Returns the value with the maximum number of repetitions. |
25 |
| - return check_list[result.index(y)] |
| 26 | + if not result: |
| 27 | + return [] |
| 28 | + y = max(result) # Gets the maximum value in the result list. |
| 29 | + # Gets values of modes |
| 30 | + result = {input_list[i] for i, value in enumerate(result) if value == y} |
| 31 | + return sorted(result) |
26 | 32 |
|
27 | 33 |
|
28 | 34 | if __name__ == "__main__":
|
29 |
| - data = [2, 3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 2, 2, 2] |
30 |
| - print(mode(data)) |
31 |
| - print(statistics.mode(data)) |
| 35 | + import doctest |
| 36 | + |
| 37 | + doctest.testmod() |
0 commit comments