def snake(width, height, pos=1): way = [pos] shift = lambda offset : lambda : pos + offset up, down, right = shift(-width), shift(width), shift(1) is_top = lambda : pos in range(1, width+1) is_bottom = lambda : pos in range(width*(height-1) + 1, width*height) is_end = lambda : pos == width*height def go(where): nonlocal pos pos = where() way.append(pos) direction = down while not is_end(): go(direction) if is_bottom(): go(right) direction = up elif is_top(): go(right) direction = down return way print(snake(5,4))
может так понятней будет
