1

I have a list of integers and I'm trying to group them into sums of thirty, and then yield an output of all the smaller groups (which now equal thirty).

I'm a python novice and the only way I can think of doing this so far is sorting the Master List, getting groups of like numbers using itertools.groupby, and then creating a bunch of conditionals to find 30. Like so:

    from itertools import groupby

    N =[1,2,3,4,3,2,3,4,6,5,3,2,4,6,4,12,2,4,5,6,7,45,23,3,4,6,22,5,4,3,21,3,4,11]
    N.sort()

   print ([list(j) for i, j in groupby(N)])

Obviously, I already foresee some problems, not the least of which is that this code is extremely inefficient.

I was hoping for some suggestions to create a code that would group integers to sum to thirty without replacement - so once a integer is assigned to a group it cannot be reused.

So, given a list of L = [12,18,2,22,14,6,4,7,5]

I would get the output: [12,18] [2,22,6] [14,4,7,5]

Also just a side question:

The Master List is actually the values of a dictionary. Once these values are regrouped, do they preserve their respective keys? I hope to eventually have the output be the keys of the values grouping to thirty.

So referring back to the top example:

So, given a dictionary of L = {"A":12,"B":18,"C":2,"D":22,"E":14,"F":6,"G"4,"H":7,"I":5}

I would get the output: [A,B] [C,D,F] [E,G,H,I]

Thank you in advance!!

BMENRohan
  • 25
  • 5
  • could you plz post the output /result that you want to get? – SuperNova Jun 02 '16 at 16:22
  • I think you need to write your own function. GroupBy is useful when you have an iterable of iterables as in this example:http://stackoverflow.com/a/7286/3885927 Give it a try and ask for help if you get stuck – user3885927 Jun 02 '16 at 16:48
  • Can you always guarantee that your input can be split into even groups of 30? – Jenner Felton Jun 02 '16 at 17:00
  • Thank you @user3885927, this is a great I'll try and do that! – BMENRohan Jun 02 '16 at 17:44
  • @JennerFelton No, the list might have remaining numbers that won't add up to 30, but I'd have those come out in a separate list of "remainders." – BMENRohan Jun 02 '16 at 17:46
  • @BMENRohan Are you trying to guarantee the maximum number of possible sum to 30 combinations? If you do what you are currently doing (sorting and grouping from smallest to largest), you will end up with a bunch of numbers that "could" have made more groups, but didn't because your method uses up the small numbers first. Does that make sense? – Jenner Felton Jun 02 '16 at 17:51
  • @JennerFelton Ohh, okay I understand. For my purposes, it doesn't really matter how many groups come out as a result, so long as every group's sum = 30 and no number is used more than once. – BMENRohan Jun 02 '16 at 17:55

0 Answers0