HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Splitting an array of numbers into all possible combinations

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
allarrayintonumberscombinationssplittingpossible

Problem

This takes an array of numbers then splits it into all possible combinations of the number array of size 4 then in another array puts the leftovers. As I want to take the difference in averages of the first column and the second.

import itertools

#defines the array of numbers and the two columns
number = [53, 64, 68, 71, 77, 82, 85]
col_one = []
col_two = []

#creates an array that holds the first four
results = itertools.combinations(number,4)

for x in results:
    col_one.append(list(x))

#attempts to go through and remove those numbers in the first array
#and then add that array to col_two
for i in range(len(col_one)):
    holder = list(number)
    for j in range(4):
        holder.remove(col_one[i][j])
    col_two.append(holder)  

col_one_average = []
col_two_average = []

for k in col_one:
    col_one_average.append(sum(k)/len(k))

for l in col_two:
    col_two_average.append(sum(l)/len(l))

dif = []

for i in range(len(col_one_average)):
    dif.append(col_one_average[i] - col_two_average[i])

print dif


So for example, if I have

a = [1,2,3]


and I want to split it into an array of size 2 and 1, I get

col_one[0] = [1,2]


and

col_two[0] = [3]


then

col_one[1] = [1,3]


and

col_two[1] = [2]


After I get all those I find the average of col_one[0] - average of col_two[0].

I hope that makes sense. I'm trying to do this for a statistics class, so if there is a 'numpy-y' solution, I'd love to hear it.

Solution

import itertools
import numpy

number = [53, 64, 68, 71, 77, 82, 85]

results = itertools.combinations(number,4)
# convert the combination iterator into a numpy array
col_one = numpy.array(list(results))

# calculate average of col_one
col_one_average = numpy.mean(col_one, axis = 1).astype(int)

# I don't actually create col_two, as I never figured out a good way to do it
# But since I only need the sum, I figure that out by subtraction
col_two_average = (numpy.sum(number) - numpy.sum(col_one, axis = 1)) / 3

dif = col_one_average - col_two_average

print dif

Code Snippets

import itertools
import numpy

number = [53, 64, 68, 71, 77, 82, 85]


results = itertools.combinations(number,4)
# convert the combination iterator into a numpy array
col_one = numpy.array(list(results))

# calculate average of col_one
col_one_average = numpy.mean(col_one, axis = 1).astype(int)

# I don't actually create col_two, as I never figured out a good way to do it
# But since I only need the sum, I figure that out by subtraction
col_two_average = (numpy.sum(number) - numpy.sum(col_one, axis = 1)) / 3

dif = col_one_average - col_two_average

print dif

Context

StackExchange Code Review Q#1121, answer score: 9

Revisions (0)

No revisions yet.