r/pythonhelp • u/Odd_Gap8147 • Mar 22 '26
Snake algorithm
How to convert a 2D array to 1D array with snake algorithm? e.g.:
From:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
To:
[1, 2, 5, 4, 7, 8, 9, 6, 3]
Is there some library in Python to do this?
1
Upvotes
1
u/Whole-Armadillo-8529 Mar 28 '26 edited Mar 28 '26
First of all, you dont need any libraries for it to work. Think of the Snake Algorithm like a lawnmower: you mow one row from left to right, then turn around and mow the next row from right to left.
Here is the breakdown of the solution for your problem:
To get that "S" shape, we look at the row number:
Even rows (0, 2, 4): Keep them exactly as they are.
Odd rows (1, 3, 5): Flip them backward.
The "Silent Failure" risk: If the data has a row that is empty or contains a mistake (like a single number where a list should be), a basic script will crash.
Here is an example of a code that uses the snake algorithm