Created
November 12, 2024 12:17
-
-
Save Tusenka/2e09747194f2ce9b85f54af95334ca0b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why 5<4 in the second case?
https://www.hackerrank.com/challenges/almost-sorted/problem