gunjanpatait
gunjanpatait

Reputation: 91

print an array with all the possible mean

Suppose I have a list 'a'. Now, I want to print a list with all the possible mean(only integers) from all the possible pairs of list 'a'.For example:

     a = [0,0,3,4,1,2,9]

Now, I want to print a list b such that;

     b = [0,2,1,2,1,2,6,3,5]

If (a,b) is taken as a pair then (b,a) wont count. But it would count if there are duplicates of a and b present.

Upvotes: 2

Views: 47

Answers (2)

Zev
Zev

Reputation: 3491

You have a few tasks to accomplish:

  1. Given the input, output the combinations
  2. Given the combinations output their means
  3. Given the means, filter out the non-integers

Using functional programming style you can use function composition to put each step inside the other.

from itertools import combinations
from statistics import mean
a = [0,0,3,4,1,2,9]
b = list(filter(lambda x: isinstance(x, int), map(mean, combinations(a, 2))))

Upvotes: 0

user3483203
user3483203

Reputation: 51155

You could use itertools.combinations():

import itertools
a = [0,0,3,4,1,2,9]  
av = [int(sum(i)/2) for i in itertools.combinations(a, 2) if sum(i)%2 == 0]

Output:

[0, 2, 1, 2, 1, 2, 6, 3, 5]

Upvotes: 1

Related Questions