deep
deep

Reputation: 716

Reverse an array between given indexes

I have been asked an interview question to reverse an array. I used the following method and it worked as expected:

def reverse(array, i, j):
  if i > j: # ensure i <= j
    i, j = j, i
  while i < j:
    array[i], array[j] = array[j], array[i]
    i += 1
    j -= 1 

Now, the interviewer asked me to replace the above while loop by for and I was really confused. Please can someone help me here. Thanks in advance.

Upvotes: 2

Views: 3520

Answers (4)

simpleranchero
simpleranchero

Reputation: 4034

I think more readable example would be:

arr[i,j] = reversed(arr[i, j])

Upvotes: 0

user7881131
user7881131

Reputation:

You could forget the for loop entirely and do something like this:

def reverse(array, i, j):
    # Make sure i is less than j
    if i > j:
        i, j = j, i
    # Reverse array[i:j+1]
    section = array[i:j+1]
    section.reverse()
    array[i:j+1] = section

(The j+1 is to keep consistent with your function's behaviour; both i and j are treated as inclusive, but Python wants [inclusive, exclusive).)

Or if you want to keep the for loop in and avoid standard functions, then you could do something like this:

def reverse(array, i, j):
    # Make sure i is less than j
    if i > j:
        i, j = j, i
    # Reverse array[i:j]
    count = j - i + 1
    for offset in range(0, count // 2):
        first = i + offset
        second = j - offset
        array[first], array[second] = array[second], array[first]

Upvotes: 1

VMRuiz
VMRuiz

Reputation: 1981

This is not a for, but you can also do this:

If you follow the python logic where [i:j] means i <= x < j then you can do this:

array[i:j] = array[j-1:i-1:-1]

Other way, if you want to get the elements where i <= x <= j then you can do as @darksky suggested:

array[i:j+1] = array[j: i - 1: -1]

Upvotes: 3

Sam Chats
Sam Chats

Reputation: 2321

Other answers here perform this in a really smart way, but a for loop should look something like:

for x in range(j - i):
    array[i+x], array[j-x] = array[j-x], array[i+x]

Upvotes: 1

Related Questions