-1

I have a list of numbers. I want to group this up to 5 groups and the total size of each group should be as small as possible. What would be a good approach to this?

Sample data

numbers = [52, 86, 102, 122, 964, 1075, 1420]

Possible result

result = [[1420],[1075],[964],[122, 52],[102, 86]]
maxjunerd
  • 1
  • 1

1 Answers1

0

I had a similar situation to you in the past. What I did was implement:

def lazy_split(iter_: Iterable, split_num: int) -> list[Iterable]:
    k, m = divmod(len(iter_), split_num)
    return [iter_[i*k+min(i, m):(i+1)*k+min(i+1, m)] for i in range(split_num)]

numbers = [52, 86, 102, 122, 964, 1075, 1420]
print(lazy_split(numbers, 5))
# Output: [[52, 86], [102, 122], [964], [1075], [1420]]

It is a slightly modified version of tixxit's answer to a similar question: https://stackoverflow.com/a/2135920 I called it lazy_split as it attempts to slice the iterable instead of iterating through it.

Nater0214
  • 3
  • 4