queue = [[1, 2, 3, 4, 5]] path = {str(queue[0]): []} while queue: x = queue.pop(0) for i in range(1, 6): y = x[:i][::-1] + x[i:] for j in range(i): y[j] = y[j] - 5 if y[j] > 5 else y[j] + 5 if str(y) not in path: path[str(y)] = path[str(x)] + [i] queue += [y] print(path[str([5, 4, 3, 2, 1])])