# 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 < b > c < d > e < 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) > 1:
print(array, array[-1], sep = " ", end= " ")
array.pop(0)
if array: array.pop(-1)
print(array)

• (Hint: There is a cleaner solution utilizing zip) – Dair Jun 1 at 20:44
• I'm not sure if you sure my update as I just changed it... – EML Jun 1 at 20:45
• Actually on second thoughts, I'm wrong, but you're not supposed to update code. Updated code is supposed to be a new question as per the FAQ. – Dair Jun 1 at 20:50
• Sorry. As no one had replied I thought it'd be ok. I think you replied as I updated it – EML Jun 1 at 20:53
• @Dair You can edit code before answers have been posted. There are some edge cases, but I don't think they're relevant here. – Peilonrayz Jun 1 at 22:05

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

>>> zigzag([1, 2, 3, 4])
[1, 4, 2, 3]
>>> zigzag([1, 2, 3, 4, 5])
[1, 5, 2, 4, 3]

• How come you have written [:-half]? What is with the minus sign? Thanks – EML Jun 1 at 21:41
• I worked it out. I can see if I don't put the minus sign the sliced list is too short for lists of odd length if there is no minus sign – EML Jun 1 at 21:51
• @EML It's short hand for values[:len(values) - half]. values[-half:] takes the last half amount of items. values[:-half] takes the first len(values) - half items - which is 2 in the first example and 3 in the second. – Peilonrayz Jun 1 at 21:56