1
\$\begingroup\$

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[0], array[-1], sep = " ", end= " ")
    array.pop(0)
    if array: array.pop(-1)
print(array[0])
\$\endgroup\$
  • \$\begingroup\$ (Hint: There is a cleaner solution utilizing zip) \$\endgroup\$ – Dair Jun 1 at 20:44
  • \$\begingroup\$ I'm not sure if you sure my update as I just changed it... \$\endgroup\$ – EML Jun 1 at 20:45
  • \$\begingroup\$ 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. \$\endgroup\$ – Dair Jun 1 at 20:50
  • \$\begingroup\$ Sorry. As no one had replied I thought it'd be ok. I think you replied as I updated it \$\endgroup\$ – EML Jun 1 at 20:53
  • \$\begingroup\$ @Dair You can edit code before answers have been posted. There are some edge cases, but I don't think they're relevant here. \$\endgroup\$ – Peilonrayz Jun 1 at 22:05
1
\$\begingroup\$

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]
\$\endgroup\$
  • \$\begingroup\$ How come you have written [:-half]? What is with the minus sign? Thanks \$\endgroup\$ – EML Jun 1 at 21:41
  • 1
    \$\begingroup\$ 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 \$\endgroup\$ – EML Jun 1 at 21:51
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ – Peilonrayz Jun 1 at 21:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.