Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Second solution in Clear category for Zigzag Array by colinmcnicholl
from typing import List
from itertools import count, islice
def create_zigzag(rows: int, cols: int, start: int = 1) -> List[List[int]]:
"""Input: Two ints rows and cols. And one optional argument start.
Function creates a list of lists that represents a two-dimensional grid
with the given number of rows and cols. This grid should contain the
integers from start to start + rows * cols - 1 in ascending order, but
so that the elements of every odd-numbered row are listed in
descending order, so that when read in ascending order, the numbers
zigzag through the two-dimensional grid.
Output: List of lists.
"""
iter = count(start)
return [list(islice(iter, cols))[::pow(-1, row)] for row in range(rows)]
if __name__ == '__main__':
print("Example:")
print(create_zigzag(3, 3, 5))
# These "asserts" are used for self-checking and not for an auto-testing
assert create_zigzag(3, 5) == [
[1,2,3,4,5],
[10,9,8,7,6],
[11,12,13,14,15]
]
assert create_zigzag(5, 1) == [
[1],
[2],
[3],
[4],
[5]
]
assert create_zigzag(3, 3, 5) == [
[5, 6, 7],
[10, 9, 8],
[11, 12, 13]
]
# Edge cases
assert create_zigzag(0, 3) == []
assert create_zigzag(3, 0) == [[], [], []]
assert create_zigzag(0, 0) == []
print("Coding complete? Click 'Check' to earn cool rewards!")
Jan. 29, 2019
Comments: