Zig-zag array - solution The problem


  For any given array, find a corresponding zig-zag array such the each
  element (a,b,c,d,e...) follows the rule:

a &lt; b &gt; c &lt; d &gt; e &lt; f



In other words, every other element is greater than both of its neighbouring elements and the remaining elements are smaller than their neighbours.

For example, for the list:

[4, 3, 7, 8, 6, 2, 1]


the output is:

[1 8 2 7 3 6 4]


My solution

array = [4, 3, 7, 8, 6, 2, 1]
array.sort()

while len(array) &gt; 1:
    print(array[0], array[-1], sep = " ", end= " ")
    array.pop(0)
    if array: array.pop(-1)
print(array[0])
You can just use Python's slice notation. It allows you to pass steps, which allows you to do this with ease.

I also think it's fairly easy to understand.

def zigzag(values):
    half = len(values) // 2
    new = [None] * len(values)

    new[0::2] = values[:-half]
    new[1::2] = values[-half:][::-1]
    return new


&gt;&gt;&gt; zigzag([1, 2, 3, 4])
[1, 4, 2, 3]
&gt;&gt;&gt; zigzag([1, 2, 3, 4, 5])
[1, 5, 2, 4, 3]