The "Almost Sorted" problem from HackerRank:
Given an array with \$n\$ elements, can you sort this array in ascending order using only one of the following operations?
- Swap two elements.
- Reverse one sub-segment.
Output format
If the array is already sorted, output
yes
on the first line. You do not need to output anything else.If you can sort this array using one single operation (from the two permitted operations) then output
yes
on the first line and then:
If you can sort the array by swapping \$d_l\$ and \$d_r\$, output
swap l r
in the second line. \$l\$ and \$r\$ are the indices of the elements to be swapped, assuming that the array is indexed from \$1\$ to \$n\$.Else if it is possible to sort the array by reversing the segment \$d[l\ldots r]\$, output
reverse l r
in the second line. \$l\$ and \$r\$ are the indices of the first and last elements of the subsequence to be reversed.If an array can be sorted by either swapping or reversing, stick to the swap-based method.
If you cannot sort the array in either of the above ways, output
no
in the first line.
I am trying to improve my Python so I would appreciate if somebody could review the following piece of code. I know it can be done with less code in Python, I am just not sure how.
import sys
def checkSorted(arr):
return all(arr[i] <= arr[i+1] for i in range(len(arr)-1))
def almostSorted(arr):
if len(arr) == 1 or checkSorted(arr):
print("yes")
return
# Find first item out of order from the left
i = 0
while i < len(arr) - 1 and arr[i] < arr[i+1]:
i+=1
first_ooo_left = i
# Find first item out of order from the right
i = len(arr) - 1
while i > 0 and arr[i-1] < arr[i]:
i-=1
first_ooo_right = i
# Same item?
if (first_ooo_left == first_ooo_right):
print("no")
return
l = first_ooo_left
r = first_ooo_right
swaps = 0
while r-l > 0:
if arr[l] > arr[r]:
arr[r], arr[l] = arr[l], arr[r]
swaps += 1
r-=1
l+=1
sorted = checkSorted(arr)
if sorted:
if swaps == 1:
print("yes")
print("swap " + str(first_ooo_left+1) + " " + str(first_ooo_right+1))
elif swaps == (first_ooo_right-first_ooo_left+1)//2:
print("yes")
print("reverse " + str(first_ooo_left+1) + " " + str(first_ooo_right+1))
else:
print("no")