I have a sorted list which looks as below:
mylist = [-2, -2, 1, 1, 4, 4, 3, 3, 3]
The list is sorted in ascending order based upon the number of times it appears. In case of a tie, the list is sorted based upon the values.
I need to convert this list into a square matrix of equal chunks(3*3 in this case) such that the numbers are placed "diagonally" starting from the bottom right corner.
The general case is to divide the list in equal chunks.
Desired Output:
res = [[3, 3, 4],
[3, 4, 1],
[1, -2, -2]]
I have written the below code but still not able to get the desired output:
def create_matrix(lst, n):
for i in range(0, len(lst), n):
print(i)
yield lst[i: i+n]
m = create_matrix(mylist, 3)
print(list(m))
One solution could be to place pairs in queue/stack and then pop as needed.