4
\$\begingroup\$

I am solving interview questions from here.

Problem : Given an array of integers, sort the array into a wave like array and return it, in other words, arrange the elements into a sequence such that a1 >= a2 <= a3 >= a4 <= a5.

Note - If there are multiple answers possible than return the one that is lexicographically smallest.

Approach : First sort the array then swap every second number with previous number.

This is my solution:

def wave(array):
    """Returns array in wave pattern by first sorting
    the array and then swapping the adjacent digits"""

    array.sort()  ##sort the given array
    for i in range(0,(len(array)-1),2):  ##skip every second number
        array[i], array[i+1] = array[i+1], array[i]  ##swap adjacent numbers

    return array


print wave([6,7,8,1,2,3,4])
print wave([5,1,3,4,2])
print wave([11,3,5,2,7,1,6,8,10,9,4])

How can i make this code better? Is there any other approach to solve this problem?

\$\endgroup\$
2
  • \$\begingroup\$ Where has the variable A appeared from? \$\endgroup\$
    – Josiah
    May 16, 2018 at 6:48
  • \$\begingroup\$ @josiah edited, was working on two diff. platforms typo error \$\endgroup\$ May 16, 2018 at 6:52

1 Answer 1

2
\$\begingroup\$

Because of the lexicographically smallest tie breaker restriction, you're basically funelled down this approach. In particular, you can't do without the sort.


"""Returns array in wave pattern by first sorting
the array and then swapping the adjacent digits"""

Docstrings are interface level documentation. They should describe what a function does, not how it does it. For a description of how a given implementation works, use comments.


array.sort()  ##sort the given array

Consider whether it's appropriate to do this in place (and so mangle the input array) or whether it would be better to use sorted


for i in range(0,(len(array)-1),2):  ##skip every second number
    array[i], array[i+1] = array[i+1], array[i]  ##swap adjacent numbers

You could rewrite this generators or using various tools from itertools if you wanted to avoid the explicit for loop.

However, what you have is clearer about what's going on and, given that you are working from a list already, reasonable in terms of performance.


print wave([6,7,8,1,2,3,4])
print wave([5,1,3,4,2])
print wave([11,3,5,2,7,1,6,8,10,9,4])

I note that you're only checking odd length lists with no negatives and no duplicates. Consider more comprehensive testing.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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