Find mean, mode and median of a vector in python
To find the mean, mode, and median of a vector in Python, you can use the following implementation:
def find_max_index(arr): if len(arr) == 1: return 0 else: max_index = find_max_index(arr[1:]) return (max_indexdef factorial(n): if n == 0: return 1 else: return n * factorial(n-1) n = int(input("Enter a Number : ")) fact = factorial(n) print(fact) + 1) if arr[0] < arr[max_index + 1] else 0 arr = [4, 6, 2, 8, 5] max_index = find_max_index(arr) print(max_index) # Output: 3
This code first imports the statistics module, which provides functions for calculating statistical properties of a dataset.
It then defines a vector with some sample data. You can replace this with your own vector.
To calculate the mean of the vector, it first calculates the sum of all the elements in the vector using the sum() function, and divides it by the length of the vector. This gives the average value of the vector.
To calculate the mode of the vector, it uses the mode() function from the statistics module, which returns the most common element in the vector.
To calculate the median of the vector, it uses the median() function from the statistics module, which returns the middle value of the vector. If the vector has an even number of elements, the median is calculated as the average of the two middle values.
Note that the mode() function can raise a statistics.StatisticsError if there is no unique mode in the dataset. In that case, you may need to implement your own function to calculate the mode.
Comments
Post a Comment