How to best optimize this code ?
Problem Description:
Input(counts
) is an array of \$n\$ integers, where each counts[i]
, (\$0\le i< n\$) denotes the total number of elements in a particular group that element i belongs to. For example, if counts = [3, 3, 3, 3, 3, 1, 3]
, then there are three groups; elements 0, 1, 2, 3, 4, and 6 are in one of two 3-element groups, and element 5 is in a 1-element group.
A group is valid if all the elements in the group have minimal ID numbers. In other words, a group of size \$k\$ must contain the \$k\$ smallest ID numbers belonging to a group of that size with respect to the smallest element ID in the group. For example, if counts = [3, 3, 3, 3, 3, 1, 3]
, then the grouping [0, 1, 2]
, [3, 4, 6]
, and [5]
is valid; however, the grouping [0, 1, 4]
, [2, 3, 6]
, and [5]
is not valid because the group [0, 1, 4]
does not contain the three smallest element IDs for the set of element IDs belonging to 3-element groups (i.e., \${0,1,2,3,4,6}\$).
It is guaranteed that a valid grouping always exists for the given input array.
VALID GROUPING:
0 1 2
3 4 6
5
INVALID GROUPING:
0 1 4
2 3 6
5
Sample Input (1):
counts = [2,1,1,2,1]
Sample Output (1):
0 3
1
2
4
Sample Input (2):
counts = [4,2,4,5,5,4,4,5,5,2,5,7,1,7,1,7,1,7,1,7,1,7,1,7,5,5,5,5,5]
Sample Output (2):
0 2 5 6
1 9
3 4 7 8 10
11 13 15 17 19 21 23
12
14
16
18
20
22
24 25 26 27 28
Code:
from collections import OrderedDict
def groupCount(counts):
group_dict = OrderedDict()
for i in range(len(counts)):
if counts[i] in group_dict.keys():
group_dict[counts[i]].append(i)
else:
group_dict[counts[i]] = [i]
op_list = []
for key in group_dict:
prnt_count = 0
temp_list = []
while len(group_dict[key])!=0:
prnt_count += 1
temp_list.append(group_dict[key].pop(0))
if prnt_count % key == 0:
op_list.append(temp_list)
temp_list = []
op_list.sort(key=lambda x: x[0])
for value in op_list:
print(*value, sep=' ')