This way of doing work make the code hard to read. What about using 2 ndarray of 5 int. One ndarray for the old order and one for the new order. This will remove 10 variables and make the code more clear I think. It will make taking the max easier too. You could make count_running_memory() return also an 5 int ndarray. Then you take the elemwise maximum over the ndarray.