Skip to content

Instantly share code, notes, and snippets.

@Lezalith
Created February 6, 2025 21:17
Show Gist options
  • Save Lezalith/eee907406d87a01edcf4b793e2762834 to your computer and use it in GitHub Desktop.
Save Lezalith/eee907406d87a01edcf4b793e2762834 to your computer and use it in GitHub Desktop.
Sorting a list for grid viewing purposes
def reorder_list_for_grid(lst, transpose=False, right_to_left=False, bottom_to_top=False, rows=3, cols=3):
"""
Reorder a list of numbers intended for a grid so that when the grid is filled
in standard order (left-to-right, top-to-bottom) the numbers appear in the positions
as if they were filled according to the given instructions.
Parameters:
lst: list
The list of numbers to be reordered. Its length must equal rows * cols.
transpose: bool
If False, fill rows first then columns. If True, fill columns first then rows.
right_to_left: bool
If False, fill left-to-right; if True, fill right-to-left.
bottom_to_top: bool
If False, fill top-to-bottom; if True, fill bottom-to-top.
rows: int, optional
Number of rows in the grid (default is 3).
cols: int, optional
Number of columns in the grid (default is 3).
Returns:
list: The reordered list.
"""
# Determine the intended order of cell coordinates based on the flags.
if not transpose:
# Outer loop: rows; inner loop: columns.
row_order = list(range(rows))
if bottom_to_top:
row_order = row_order[::-1] # reverse row order if bottom_to_top flag is True
col_order = list(range(cols))
if right_to_left:
col_order = col_order[::-1] # reverse column order if right_to_left flag is True
intended_order = [(r, c) for r in row_order for c in col_order]
else:
# Outer loop: columns; inner loop: rows.
col_order = list(range(cols))
if right_to_left:
col_order = col_order[::-1]
row_order = list(range(rows))
if bottom_to_top:
row_order = row_order[::-1]
intended_order = [(r, c) for c in col_order for r in row_order]
# Create a mapping from grid coordinate to the number that should go there.
grid_mapping = {}
for index, coord in enumerate(intended_order):
grid_mapping[coord] = lst[index]
# print("Grid mapping: {}".format(grid_mapping))
# Build the sorted list by reading the grid in standard order (row-major).
standard_order = [(r, c) for r in range(rows) for c in range(cols)]
sorted_list = [grid_mapping[coord] for coord in standard_order]
return sorted_list
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment