2

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.

user3483203
  • 50,081
  • 9
  • 65
  • 94

2 Answers2

1

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]
user3483203
  • 50,081
  • 9
  • 65
  • 94
  • Thank you. summed up. can this be done without itertools? – gunjanpatait Apr 15 '18 at 00:49
  • Yes, you could just implement your own combination function, but using itertools is much easier. – user3483203 Apr 15 '18 at 00:57
  • yes, you'd just need to create a function that spits out all the combinations. Try it out and see what you come up with. Share what you did and post again if you get stuck. Also, @darxtrix's answer on this question should help: https://stackoverflow.com/questions/464864/how-to-get-all-possible-combinations-of-a-list-s-elements – Zev Apr 15 '18 at 00:59
0

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))))
Zev
  • 3,423
  • 1
  • 20
  • 41