Array partitioning into unequal groups

In python, an array is given:

a = [ 0, 1, 3, 4, 6, 7, 8, 10, 14 ] 

I would like to break this down into three unequal groups, so that I get something like this:

 b = [0, 1, 3, 4] c = [6, 7, 8] d = [10, 14] 

I want to group numbers in multiples of 5. Thus, any integers from 0 to 4 fall into the first array, 5 - 9 in the second, etc.

+4
source share
3 answers

Itertools.groupby is always the answer!

Here we round each number to the nearest 5, and then group by equal numbers:

 >>> for n, g in itertools.groupby(a, lambda x: round(x/5)*5): print list(g) [0, 1, 3, 4] [6, 7, 8] [10, 14] 
+3
source

We can be more or less effective in time if we know something about the numbers we work with. We could also come up with a very fast one that is terribly inefficient in memory, but think about it if it fits your goals:

 #something to store our new lists in range = 5 #you said bounds of 5, right? s = [ [] ] for number in a: foundit = false for list in s: #deal with first number if len( list ) == 0: list.append( number ) else: #if our number is within the same range as the other number, add it if list[0] / range == number / range: foundit = true list.append( number ) if foundit == false: s.append( [ number ] ) 
0
source

Now that I have a better understanding of your definition of groups, I think this relatively simple answer will not only work, but also very quickly:

 from collections import defaultdict a = [0, 1, 3, 4, 6, 7, 8, 10, 14] chunk_size = 5 buckets = defaultdict(list) for n in a: buckets[n/chunk_size].append(n) for bucket,values in sorted(buckets.iteritems()): print '{}: {}'.format(bucket, values) 

Output:

 0: [0, 1, 3, 4] 1: [6, 7, 8] 2: [10, 14] 
0
source

Source: https://habr.com/ru/post/1483901/


All Articles