Skip to content

Instantly share code, notes, and snippets.

@Tusenka
Created November 12, 2024 12:17
Show Gist options
  • Save Tusenka/2e09747194f2ce9b85f54af95334ca0b to your computer and use it in GitHub Desktop.
Save Tusenka/2e09747194f2ce9b85f54af95334ca0b to your computer and use it in GitHub Desktop.
What is wrong with the code. Why it writes 5<4?
```
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'almostSorted' function below.
#
# The function accepts INTEGER_ARRAY arr as parameter.
#
def _findFirstUnsorted(arr):
for i in range(0, len(arr)-1):
if arr[i]>arr[i+1]:
return i
else:
return None
def _findSwap(arr, index):
i=len(arr)-1
if index==0:
bound=[-1, arr[index+1]]
else:
bound=[arr[index-1], arr[index+1]]
while i >=index:
if bound[0]<=arr[i] and bound[1] >= arr[i] and arr[index] <= arr[i-1]:
return i
i-=1
return None
def _findReverse(arr, index):
i=index+1
while i<len(arr):
if arr[i-i] > arr[i]:
print("reverse", arr[i-1], arr[i])
i+=1
else:
x=arr[i-1]
y=arr[i]
print("break", arr[i-1], arr[i], x < y)
break
return i
def _tryReverse(arr, index):
i=_findReverse(arr, index)
arr1=arr[0:index] + list(reversed(arr[index:i])) + arr[i:]
return i if _findFirstUnsorted(arr1) is None else None
def _trySwap(array, index):
arr1=arr[:]
i=_findSwap(arr, index)
if i is None:
return None
arr1[i], arr1[index]=arr1[index], arr1[i]
return i if _findFirstUnsorted(arr1) is None else None
def almostSorted(arr):
i=_findFirstUnsorted(arr)
if i is None:
print("yes")
return
swap=_trySwap(arr, i)
if swap is not None:
print("yes")
print("swap", i+1, swap+1)
return
reverse=_tryReverse(arr, i)
if reverse is not None:
print("yes")
print("reverse", i+1, reverse+1)
return
print("no")
if __name__ == '__main__':
n = int(input().strip())
arr = list(map(int, input().rstrip().split()))
almostSorted(arr)
```
@Tusenka
Copy link
Author

Tusenka commented Nov 12, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment