Write a function getMean that takes as parameters an array (arr) and 2 integers (x and y). The function should return the mean between the mean of the the first x elements of the array and the mean of the last y elements of the array.

The mean should be computed if both x and y have values higher than 1 but less or equal to the array's length. Otherwise the function should return -1.

getMean([1,3,2,4], 2, 3) should return 2.5 because: the mean of the the first 2 elements of the array is (1+3)/2=2 and the mean of the last 3 elements of the array is (4+2+3)/3=3 so the mean of those 2 means is (2+3)/2=2.5.

getMean([1,3,2,4], 1, 2) should return -1 because x is not higher than 1.

getMean([1,3,2,4], 2, 8) should return -1 because 8 is higher than the array's length.

Source: codewars | Difficulty: EASY
Tags: Fundamentals

Data structures

Starter code: def get_mean(arr,x,y):
	

Solutions:
def get_mean(arr, x, y):
	if 1 < x <= len(arr) and 1 < y <= len(arr):
		return (sum(arr[:x]) / x + sum(arr[-y:]) / y) / 2
	return -1


from operator import truediv

def mean(arr):
	return truediv(sum(arr), len(arr))

def get_mean(arr, x, y):
	if min(x, y) < 2 or max(x, y) > len(arr):
		return -1
	return truediv(mean(arr[:x]) + mean(arr[-y:]), 2)


def get_mean(arr, x, y):
	l = len(arr)
	if 1 < x <= l and 1 < y <= l:
		mx = sum(arr[:x]) / x
		my = sum(arr[-y:]) / y
		return (mx + my) / 2
	else:
		return -1


from statistics import mean

def get_mean(arr, x, y):
	if all((1 < i < len(arr) + 1 for i in (x, y))):
		return mean((mean(arr[:x]), mean(arr[-y:])))
	return -1


def get_mean(arr, x, y):
	from numpy import mean
	if 1 < x <= len(arr) and 1 < y <= len(arr):
		return mean((mean(arr[:x]), mean(arr[-y:])))
	else:
		return -1


def get_mean(arr, x, y):
	if x not in range(2, len(arr) + 1) or y not in range(2, len(arr) + 1):
		return -1
	return (sum(arr[:x]) / x + sum(arr[-y:]) / y) / 2


get_mean = lambda a, x, y: (1 < x <= len(a) >= y > 1) - 1 or (sum(a[:x]) / x + sum(a[-y:]) / y) / 2


def get_mean(arr, x, y):
	return -1 if min(x, y) < 2 or max(x, y) > len(arr) else (sum(arr[:x]) / x + sum(arr[-y:]) / y) / 2


get_mean = lambda arr, x, y: -1 if x < 2 or y < 2 or x > len(arr) or (y > len(arr)) else (sum(arr[:x]) / float(x) + sum(arr[-y:]) / float(y)) / 2.0


def get_mean(arr, x, y):
	if x <= 1 or y <= 1:
		return -1
	elif x > len(arr) or y > len(arr):
		return -1
	else:
		return 0.5 * (sum(arr[:x]) / x + sum(arr[-y:]) / y)