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.
array[i:j] = array[j:i:-1]array[i:j] = array[i:j][::-1]array[i:j] = array[j-1:i-1:-1]. Fora = list(range(10)),a[4:8] = a[8:4:-1]gives you[0, 1, 2, 3, 8, 7, 6, 5, 8, 9]!aafter the operation? What you're quoting is just the slicea[8:4:-1], not the result of the replace operation.