'Function that only accepts list as input and returning dictionary of statistic measures as output
I need some help with the following problem:
I've got most of the code right, just missing something with the input filtering and 3rd test input (nested list input/output). First two outputting as they should.
Function Specs:
list as input. If the function does not receive a list, it must raise a TypeError. If the length of the list is smaller than or equal to 1, raise a ValueError. Function must return a dict, whose keys represent the sample statistics of the input with the following format:
If the input list contains multiple rows, the function should report on the mean/std/max/etc of each row in the form of a list.
All numerical values should be rounded to 2 decimal places
HINT: Use numpy functions with the axis keyword. When doing an unbiased estimate, try googling the ddof keyword. The axis keyword should be either 0, 1, or -1. One of these will work better than the other.
Expected Outputs:
stats([1, 1, 1, 1]) == {'mean': 1, 'std': 0, 'min': 1, 'median', 1, 'max': 1}
stats([1, 2, 2, 3, 4]) == {'mean': 2.4, 'std': 1.14, 'min': 1, 'median': 2.0, 'max': 4}
stats([[1, 2], [3, 4]]) == {
'mean': [1.5, 3.5],
'std': [0.71, 0.71],
'min': [1, 3],
'median': [1.5, 3.5],
'max': [2, 4]
}
Error code received:
PASSED question_5_mean
PASSED question_5_mean
FAILED question_5_mean
Inputs: [[[1, 2], [3, 4]]]
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
PASSED question_5_mean
PASSED question_5_ValueError
PASSED question_5_ValueError
FAILED question_5_TypeError
Inputs: ['string input']
def test_question_5_TypeError(test_input):
FAILED question_5_TypeError
Inputs: [{'dict': 1, 'input': 2}]
def test_question_5_TypeError(test_input):
Solution 1:[1]
Try this,
def stats(lst):
if type(lst) != list:
raise TypeError("Please enter a list.")
elif len(lst) <= 1:
raise ValueError("Please enter a list with more than 1 elements.")
arr = np.array(lst)
statistics = lambda row:(row.mean(), np.median(row), row.std(), row.max(), row.min())
data = [[] for i in range(5)]
for row in range(len(arr)):
for i, item in enumerate(statistics(arr[row, :])):
data[i].append(item)
return dict(zip(("mean", "median", "std", "max", "min"), data))
stats([[1,2],[3,4]])
Output -
{'max': [2, 4],
'mean': [1.5, 3.5],
'median': [1.5, 3.5],
'min': [1, 3],
'std': [0.5, 0.5]}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Zero |
